Pattern matching
One of the widely used features of is pattern matching. Each pattern match has a set of alternatives, each of them starting with the case keyword. Each alternative has a pattern and expression(s), which will be evaluated if the pattern matches and the arrow symbol =>
separates pattern(s) from expression(s). The following is an example which demonstrates how to match against an integer:
object PatternMatchingDemo1 { def main(args: Array[String]) { println(matchInteger(3)) } def matchInteger(x: Int): String = x match { case 1 => "one" case 2 => "two" case _ => "greater than two" } }
You can run the preceding program by saving this file in PatternMatchingDemo1.scala
and then using the following commands to run it. Just use the following command:
>scalac Test.scala >scala Test
You will get the following output:
Greater than two
The cases statements are used as a function that maps integers to strings. The following is another example which...