match expressions are fun, and a key element of functional programming. When you hear people talking about “pattern matching” in Scala, this is what they’re talking about.
match expressions, like a
switch statement in Java or C:
enum CrustSize: case Small, Medium, Large import CrustSize.* val crustSize = Small // later in the code ... crustSize match case Small => println("small crust size") case Medium => println("medium crust size") case Large => println("large crust size")
Note that that example is used for the side effect of printing, and does not return a value. A better approach is to return a result from a
// if you think about the previous example, you’re combining // two actions: creating a string, and printing. // creating a string is pure, printing is impure. // better to separate them. // match is a true expression. val rez = crustSize match case Small => "small crust size" case Medium => "medium crust size" case Large => "large crust size"
Multiple lines in a case statement
Use this approach when the expression on the right side of the
=> requires multiple lines:
val rez = crustSize match case Small => // multiple lines here "small crust size" case Medium => "medium crust size" case Large => "large crust size"
Handling a default “catch all” case
Note that you don’t need a default, catch-all case in this example because the compiler is smart and knows that these are the only
Writing functions with
match expressions. Goals:
- Write a function with
- Handle the catch-all
def isTrue(a: Matchable): Boolean = a match // VERSION 1 case 0 => false case "0" => false case "" => false case false => false case _ => true