Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Case Classes and Pattern Matching

Pattern Matching in Scala

Master Scala 3 pattern matching: match expressions, literal, variable, type and tuple patterns, guards, alternatives, and how matching differs from switch.

If case classes are the data, pattern matching is how you take that data apart. A match expression compares a value against a series of patterns from top to bottom and runs the first one that fits. It looks like Java's switch, but it is far more powerful: it can test types, take values out of structures, add conditions and it returns a value.

This lesson covers the everyday patterns. The next lessons add sealed hierarchies and custom extractors.

The match expression

SCALA
def dayType(day: String): String = day match
  case "Saturday" | "Sunday" => "weekend"
  case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" => "weekday"
  case _ => "unknown"

println(dayType("Sunday"))   // weekend
println(dayType("Funday"))   // unknown

Key points:

  • match is an expression: the whole thing evaluates to the result of the chosen branch, so there is no break and no fall-through.
  • | combines alternatives in a single case.
  • _ is the wildcard. It matches anything and binds nothing.
  • Cases are tried in order, so put specific patterns before general ones.
  • If no case fits, Scala throws a MatchError at run time. The compiler can warn you when it can prove a match is incomplete, as you will see with sealed types.

Kinds of pattern

Literal Matches 0, "a", true.
Variable Binds the value to a name.
Wildcard _ matches anything.
Type n: Int tests the type.
1 / 2

Variable and literal patterns

A lowercase name in a pattern is a variable pattern: it matches anything and gives you a name for the value.

SCALA
def classify(n: Int): String = n match
  case 0 => "zero"
  case 1 => "one"
  case other => s"many ($other)"

Here other is a fresh variable that holds the matched number. To match against an existing value instead of binding a new variable, use backticks or an uppercase name:

SCALA
val expected = 42
def isExpected(n: Int): Boolean = n match
  case `expected` => true
  case _ => false

Without the backticks, case expected => would shadow the outer value and match everything, a classic beginner bug.

Type patterns

You can test the runtime type and use the value as that type in one step, which replaces instanceof plus a cast:

SCALA
def describe(x: Any): String = x match
  case i: Int => s"an Int: ${i + 1}"
  case s: String => s"a String of length ${s.length}"
  case d: Double => f"a Double: $d%.1f"
  case xs: List[?] => s"a list with ${xs.size} items"
  case null => "null!"
  case _ => "something else"

println(describe(41))       // an Int: 42
println(describe("scala"))  // a String of length 5
println(describe(List(1,2)))// a list with 2 items

Because of type erasure on the JVM, you cannot distinguish List[Int] from List[String] at run time, so write List[?] (Scala 3 syntax for "a list of anything") rather than a specific element type.

Constructor patterns

This is where case classes shine. A pattern shaped like the constructor extracts the fields:

SCALA
case class Point(x: Int, y: Int)
case class Line(from: Point, to: Point)

def kind(l: Line): String = l match
  case Line(Point(x1, y1), Point(x2, y2)) if x1 == x2 => "vertical"
  case Line(Point(_, y1), Point(_, y2)) if y1 == y2 => "horizontal"
  case Line(a, b) if a == b => "a single point"
  case _ => "diagonal"

println(kind(Line(Point(1, 1), Point(1, 9))))  // vertical

Patterns nest to any depth: the first case tests that l is a Line, that both ends are Points and binds four numbers, all in one line.

Guards

A guard is an if condition after the pattern. The case matches only if the pattern fits and the condition is true:

SCALA
def grade(score: Int): Char = score match
  case s if s >= 90 => 'A'
  case s if s >= 80 => 'B'
  case s if s >= 70 => 'C'
  case _ => 'F'

Use guards for conditions that cannot be expressed as a pattern. Keep them cheap and free of side effects, because the compiler cannot reason about them when checking completeness.

Tuples, lists and alternatives

SCALA
def compare(pair: (Int, Int)): String = pair match
  case (a, b) if a == b => "equal"
  case (a, b) if a < b => "ascending"
  case _ => "descending"

def firstTwo(xs: List[Int]): String = xs match
  case Nil => "empty"
  case x :: Nil => s"just $x"
  case x :: y :: rest => s"$x, $y and ${rest.size} more"

:: is the "cons" constructor of an immutable List, so x :: rest splits head and tail. You can also write List(a, b) or List(first, _*) where _* matches the remaining elements. The recursion-friendly head/tail split appears constantly in functional code.

You can bind a whole sub-pattern to a name with @:

SCALA
def keepWhole(p: (Int, Int)): String = p match
  case whole @ (0, _) => s"starts at zero: $whole"
  case _ => "other"

match as an expression, and Option

Because match returns a value, you can use it anywhere an expression fits:

SCALA
val config: Option[String] = Some("dark")
val label = config match
  case Some(theme) => s"Theme: $theme"
  case None => "Theme: default"
println(label)   // Theme: dark

Matching on Option is the idiomatic way to deal with missing values. See Option, Either and Try for the richer toolbox.

Not just for classes

Patterns also work in:

  • val definitions: val (a, b) = (1, 2)
  • for loops: for (name, age) <- people do println(name)
  • Partial function literals: list.collect { case n: Int if n > 0 => n }
  • try/catch: catch case e: NumberFormatException => 0

The same idea on the JVM

Java 21+ has pattern matching for switch and Kotlin has when with is. Both are not Scala, but they run on our site and show the shape of the idea.

Java Java: switch with type and record patterns (Java, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Kotlin Kotlin: when with smart casts and ranges (Kotlin, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Lowercase constants in patterns. case max => binds a new variable named max. Use backticks or an uppercase constant.
  • Forgetting the wildcard and getting a MatchError for an unexpected input.
  • Ordering. A broad case such as case n: Int placed first hides all later Int cases; the compiler warns about unreachable cases.
  • Specific generic types. case xs: List[Int] is checked only as List[?] at run time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a match expression evaluate to?

    match is an expression. The first matching case is chosen and its result becomes the value of the whole match.
  2. 2. What happens with val limit = 10; x match { case limit => ... }?

    A lowercase identifier in a pattern is a variable pattern. Use backticks, as in limit, to compare against the existing value.
  3. 3. Which pattern matches a list with at least two elements and binds the first two?

    x :: y :: rest splits off two elements from the front of the list. (x, y) would match a tuple instead.
  4. 4. Why should you write case xs: List[?] instead of case xs: List[Int]?

    On the JVM the element type is erased, so only the List part can be tested at run time.

Summary

  • match is an expression with ordered cases, no fall-through, and _ as the catch-all.
  • Pattern kinds: literal, variable, wildcard, type, constructor, tuple, list, alternative (|), binder (@).
  • Guards (if) add conditions; backticks match an existing value.
  • Patterns work in val, for, catch and partial functions too.
  • Unmatched values cause MatchError, which sealed types help the compiler prevent.

Next: Enums and Sealed ADTs