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

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:

  1. Guard Conditions
Syntax
scala
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

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))
}
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
  1. Putting the guard's if after the arrow, as in case x => if x < 0, when it comes before =>.
  2. Putting a guarded case after a general one, so the guard is never checked.
  3. 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:

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.