Match Expression
Match expression in Scala is similar to Switch in Java.
In Match expression, a single input item is evaluated and the first pattern that is “matched” is executed and its value returned.
In Scala, there is no “fall-through” from one pattern to the next one in line, nor is there a “break” statement that would prevent this fall-through.
Syntax of Match Expression
<expression> match {
case <pattern match> => <expression>
[case...]
}
Example 1
Here is a simple example that uses match for comparing a value:
val num = 11; num match { case 10 => println("nummber is 10"); case _ => println("number other than 10"); }
Output
Since number is not 10, the output will be :
number other than 10
Example 2
Match expression can return a value. Let’s see an example to find if a number is even or odd, using Match expression:
val num = 20; val check = (num % 2 == 0) match { case true => "Even"; case false => "Odd"; } println(check);
Output
Even
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post