Guard Conditions
A guard adds an extra condition to a match case, like a bouncer who checks your ticket and also your age. The case only counts when the rule is true as well.
In this page:
Syntax
value match {
case x if condition => expression
case _ => default_result
}
Guard Conditions
A guard, written as case pattern if condition =>, adds an extra boolean check to a pattern that must also be true for that branch to match.
If the guard's condition is false, matching continues on to the next case as if the pattern hadn't matched at all. Guards let you express conditions that plain structural patterns alone can't capture.
Note:
A guard's condition can reference variables bound earlier in the same pattern, like
case Point(x, y) if x == y => ....Example: Guard Conditions
object Main extends App {
def classify(n: Int): String = n match {
case x if x < 0 => "negative"
case 0 => "zero"
case x if x % 2 == 0 => "positive even"
case _ => "positive odd"
}
println(classify(-5))
println(classify(0))
println(classify(4))
println(classify(7))
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Putting the guard's
ifafter the arrow, as incase x => if x < 0, when it comes before=>. - Putting a guarded case after a general one, so the guard is never checked.
- Assuming the guard runs for all cases, when it applies only to the case it is attached to.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: