Guard Conditions
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: