0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Guards and Binding

Conditions in matches.

Guards and Binding is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit. This is lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, and your progress syncs across the web and the CoddyKit app. The Scala for Backend Engineering & Functional Programming course includes 4 lessons in total.

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

Binding Then Guarding

The guard can reference the name you bound in the pattern. This is how you test properties of the matched value.

object Main {
  def fizz(n: Int): String = n match {
    case x if x % 15 == 0 => "FizzBuzz"
    case x if x % 3 == 0  => "Fizz"
    case x if x % 5 == 0  => "Buzz"
    case x                => x.toString
  }
  def main(args: Array[String]): Unit = {
    println(fizz(15))
    println(fizz(9))
    println(fizz(7))
  }
}

Guards on Ranges

Guards are perfect for ranges, which literal patterns cannot express directly.

object Main {
  def band(score: Int): String = score match {
    case s if s >= 90 => "A"
    case s if s >= 80 => "B"
    case s if s >= 70 => "C"
    case _            => "F"
  }
  def main(args: Array[String]): Unit = {
    println(band(95))
    println(band(83))
    println(band(60))
  }
}

Pattern Binding With @

The @ symbol binds the whole matched value to a name while still pattern matching its structure.

Here whole @ pattern means: match pattern, and also call the matched value whole.

object Main {
  def main(args: Array[String]): Unit = {
    val x: Any = 7
    val msg = x match {
      case n @ (_: Int) => s"int value is $n"
      case _            => "other"
    }
    println(msg)
  }
}

Binding in Collections

The @ binding is especially handy with structured patterns, like capturing a whole list while also inspecting its head.

object Main {
  def describe(xs: List[Int]): String = xs match {
    case all @ (first :: _) => s"starts with $first, full = $all"
    case Nil                => "empty"
  }
  def main(args: Array[String]): Unit = {
    println(describe(List(1, 2, 3)))
    println(describe(Nil))
  }
}

Combining Type Pattern and Guard

You can mix a type pattern with a guard. First the type is checked, then the boolean condition.

object Main {
  def label(x: Any): String = x match {
    case s: String if s.length > 3 => "long string"
    case s: String                 => "short string"
    case _                         => "not a string"
  }
  def main(args: Array[String]): Unit = {
    println(label("hello"))
    println(label("hi"))
    println(label(42))
  }
}

Multiple Conditions

A guard is just a boolean expression, so you can combine conditions with && and ||.

object Main {
  def category(age: Int): String = age match {
    case a if a >= 13 && a <= 19 => "teen"
    case a if a < 13             => "child"
    case _                       => "adult"
  }
  def main(args: Array[String]): Unit = {
    println(category(15))
    println(category(8))
    println(category(40))
  }
}

Guards Do Not Fall Through

If a pattern matches but its guard is false, Scala moves on to the next case, not the next guard of the same pattern.

Make sure a later case can catch values that fail every guard.

object Main {
  def test(n: Int): String = n match {
    case x if x > 100 => "big"
    case x            => s"not big: $x"
  }
  def main(args: Array[String]): Unit = {
    println(test(200))
    println(test(5))
  }
}

Why Guards and Binding?

Together, guards and @ bindings make pattern matching expressive:

  • Guards add conditions like ranges and divisibility
  • @ captures the whole value while destructuring it
  • They keep branching logic compact and readable

Putting It Together

This example binds the value, checks a guard, and provides a fallback.

object Main {
  def temp(c: Int): String = c match {
    case t if t >= 30 => s"hot ($t)"
    case t if t >= 15 => s"mild ($t)"
    case t            => s"cold ($t)"
  }
  def main(args: Array[String]): Unit = {
    println(temp(35))
    println(temp(20))
    println(temp(5))
  }
}

Quick Check

Test your understanding of guards and binding.

Recap

You learned to refine matches:

  • A guard is an if condition after a pattern
  • If the guard is false, matching moves to the next case
  • The @ operator binds the whole value while destructuring
  • Guards combine with type patterns and boolean operators

Frequently Asked Questions

Is the “Guards and Binding” lesson free?

Yes — the full text of “Guards and Binding” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO. The Scala for Backend Engineering & Functional Programming course includes 4 lessons in total.

What will I learn in “Guards and Binding”?

Conditions in matches. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Scala for Backend Engineering & Functional Programming?

No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Guards and Binding” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?

Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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