← Back to Scala Course | Chapter 10: Pattern Matching | Lesson 5 of 7

Guard Conditions

In this page:

  1. Guard Conditions

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

markup
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))
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.