TExcelTAD
Home › Scala › Scala Match Expressions

Scala Match Expressions

A match expression compares a value against a list of patterns and evaluates the first case that fits. Think of it as a far more powerful switch: it can match constants, types, ranges with guards, and even take data structures apart. Like if, it is an expression that returns a value.

Matching constants

scala · try it yourself
def dayName(n: Int): String = n match
  case 1 => "Monday"
  case 2 => "Tuesday"
  case 3 => "Wednesday"
  case 4 => "Thursday"
  case 5 => "Friday"
  case 6 | 7 => "Weekend"
  case _ => "Invalid day"

@main def run(): Unit =
  println(dayName(3))
  println(dayName(7))
  println(dayName(9))
Wednesday
Weekend
Invalid day
  • case 6 | 7 matches either value.
  • case _ is the wildcard: it matches anything, so it works as the default branch.
  • Cases do not fall through; only one runs, and there is no break.

Binding a variable and adding guards

A lowercase name in a pattern captures the value. A guard (if … after the pattern) adds an extra condition.

scala · try it yourself
def classify(temp: Int): String = temp match
  case t if t < 0  => s"$t°: freezing"
  case t if t < 15 => s"$t°: cold"
  case t if t < 25 => s"$t°: pleasant"
  case t           => s"$t°: hot"

@main def run(): Unit =
  List(-5, 8, 21, 33).foreach(t => println(classify(t)))
-5°: freezing
8°: cold
21°: pleasant
33°: hot

Matching on types

A pattern like n: Int succeeds only when the value has that type, and gives you a correctly typed name to work with.

scala · try it yourself
def describe(x: Any): String = x match
  case n: Int if n < 0 => s"negative int $n"
  case n: Int          => s"int $n"
  case d: Double       => f"double $d%.1f"
  case s: String       => s"string of length ${s.length}"
  case b: Boolean      => s"boolean $b"
  case other           => s"something else: $other"

@main def run(): Unit =
  println(describe(-4))
  println(describe(10))
  println(describe(2.75))
  println(describe("hey"))
  println(describe(true))
  println(describe(List(1)))
negative int -4
int 10
double 2.8
string of length 3
boolean true
something else: List(1)

Matching tuples and lists

Patterns can look inside structures. This is called destructuring.

scala · try it yourself
def fizzBuzz(n: Int): String = (n % 3, n % 5) match
  case (0, 0) => "FizzBuzz"
  case (0, _) => "Fizz"
  case (_, 0) => "Buzz"
  case _      => n.toString

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

@main def run(): Unit =
  println((1 to 15).map(fizzBuzz).mkString(" "))
  println(firstTwo(Nil))
  println(firstTwo(List(7)))
  println(firstTwo(List(1, 2, 3, 4)))
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
empty
only 7
1 and 2, plus 2 more

a :: rest reads "a list whose head is a and whose tail is rest". You will meet many more patterns in Pattern Matching in Depth.

Pattern syntax overview

Pattern Matches
42, "yes", true that exact constant
_ anything (ignored)
x (lowercase) anything, bound to x
a | b either alternative
x: String values of that type
p if cond p, but only when cond is true
(a, b) a 2-tuple
head :: tail, Nil non-empty / empty list
Some(x), None an Option
Point(x, y) a case class (extractor)

When nothing matches

If no case fits, Scala throws a MatchError at run time. Add a wildcard case, or match on a sealed type/enum so the compiler can warn you about missing cases.

Tip: Put the most specific cases first. Cases are tried top to bottom, and a broad case like case _ or case n: Int placed early would hide everything after it.

Test yourself

What does case _ => do in a match expression?

  1. Matches only null
  2. Matches anything and serves as the default
  3. Matches the empty string
  4. Ends the match

What happens after a matching case runs?

  1. Execution falls through to the next case
  2. The match expression finishes with that case's value
  3. You must write break
  4. All cases run

Which pattern matches a list with at least two elements?

  1. case a :: Nil
  2. case Nil
  3. case a :: b :: rest
  4. case List()