3.13. Adding if Expressions (Guards) to Case Statements
Problem
You want to add qualifying logic to a case statement in a match expression, such as
allowing a range of numbers, or matching a pattern, but only if that
pattern matches some additional criteria.
Solution
Add an if
guard to your case statement. Use it to match a range of
numbers:
imatch{caseaif0to9containsa=>println("0-9 range: "+a)casebif10to19containsb=>println("10-19 range: "+b)casecif20to29containsc=>println("20-29 range: "+c)case_=>println("Hmmm...")}
Use it to match different values of an object:
nummatch{casexifx==1=>println("one, a lonely number")casexif(x==2||x==3)=>println(x)case_=>println("some other value")}
You can reference class fields in your if guards. Imagine here that x is an instance of a Stock class that has symbol and price fields:
stockmatch{casexif(x.symbol=="XYZ"&&x.price<20)=>buy(x)casexif(x.symbol=="XYZ"&&x.price>50)=>sell(x)case_=>// do nothing}
You can also extract fields from case classes and use those in your guards:
defspeak(p:Person)=pmatch{casePerson(name)ifname=="Fred"=>println("Yubba dubba doo")casePerson(name)ifname=="Bam Bam"=>println("Bam bam!")case_=>println("Watch the Flintstones!")}
Discussion
You can use this syntax whenever you want to add simple matches to
your case statements on the left side of the
expression.
Note that all of these examples could be written ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access