Pattern matching

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
Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the switch statement in Java, and it can likewise be used in place of a series of if...else statements. You can find more on pattern matching by referring to the official docs of Scala (URL: http://www.scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html).

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.228.180