0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Guards and Binding

Conditions in matches.

What Is a Guard?

A guard adds a boolean condition to a case using if. The case matches only when the pattern fits and the guard is true.

Guards let a single pattern split into finer cases based on the value.

Adding an if Guard

Write the guard after the pattern: case n if n > 0 =>. If the condition is false, matching continues to the next case.

object Main {
  def sign(n: Int): String = n match {
    case x if x > 0 => "positive"
    case x if x < 0 => "negative"
    case _          => "zero"
  }
  def main(args: Array[String]): Unit = {
    println(sign(5))
    println(sign(-3))
    println(sign(0))
  }
}

All lessons in this course

  1. match Expressions
  2. Matching Types and Values
  3. Guards and Binding
  4. Deconstruction
← Back to Scala for Backend Engineering & Functional Programming