One of the widely used features of Scala 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 matches against different types:
object PatternMatchingDemo2 {
def main(args: Array[String]): Unit = {
println(comparison("two"))
println(comparison("test"))
println(comparison(1))
}
def comparison(x: Any): Any = x match {
case 1 => "one"
case "five" => 5
case _ => "nothing else"
}
}
You can run this example by doing the same for the example earlier and will get the following output:
nothing else
nothing else
one
In the next section, we will discuss an important feature in Scala that enables us a value that can be passed automatically, so to speak, or a conversion from one type to another that is made automatically.