Pattern Matching
Pattern matching allows us to make a programmatic choice between multiple conditions.
Pattern matching is an essential and powerful feature of the Scala language.
With Scala’s pattern matching, we can include types, wildcards, sequences, regular expressions in case statements.
Example of pattern matching
Here is a simple example of pattern matching in Scala :
def printNum(num:Int){ num match{ case 0 => println("Zero"); case 1 => println("One"); case _ => println("Other number"); } }
The syntax of pattern matching uses the match keyword before all the case alternatives.
The underscore (_) given in last case is wildcard in the pattern matching. It matches anything not defined in the cases above it.
Let’s test the above method for following values :
printNum(0); printNum(1); printNum(5);
Output:
Zero
One
Other number
Matching Any Type
The following example matches on values of specific types and it shows one way of writing a “default” clause that matches anything:
val anyList = List(1, 2, 2.7, "one", "two",'f' ) for (m <- anyList) { m match { case i: Int => println("Integer: " + i) case s: String => println("String: " + s) case f: Double => println("Double: " + f) case other => println("other: " + other) } }
Output:
Integer: 1
Integer: 2
Double: 2.7
String: one
String: two
other: f
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post