TExcelTAD
Home › Scala › Scala Pattern Matching in Depth

Scala Pattern Matching in Depth

You met match early in this course. Now that you know case classes, enums, tuples and collections, it is time to see the full power of patterns: nesting, binders, sequence patterns, typed patterns, custom extractors and matching outside of match.

Nested patterns and the @ binder

Patterns can be nested to any depth. Use name @ pattern to bind the whole matched value while still checking its shape.

scala · try it yourself
case class Item(name: String, price: Double)
case class Order(id: Int, items: List[Item], coupon: Option[String])

def summary(o: Order): String = o match
  case Order(id, Nil, _) =>
    s"#$id is empty"
  case Order(id, List(single @ Item(_, p)), None) if p > 100 =>
    s"#$id: one expensive item, ${single.name}"
  case Order(id, first :: _, Some(code)) =>
    s"#$id starts with ${first.name}, coupon $code"
  case Order(id, items, _) =>
    s"#$id has ${items.size} items"

@main def run(): Unit =
  println(summary(Order(1, Nil, None)))
  println(summary(Order(2, List(Item("laptop", 999)), None)))
  println(summary(Order(3, List(Item("pen", 2), Item("ink", 5)), Some("SAVE5"))))
  println(summary(Order(4, List(Item("cup", 8), Item("tea", 4)), None)))
#1 is empty
#2: one expensive item, laptop
#3 starts with pen, coupon SAVE5
#4 has 2 items

Sequence patterns

List(...), Vector(...) and Seq(...) patterns match exact lengths, and rest* captures any remaining elements.

scala · try it yourself
def parse(cmd: Seq[String]): String = cmd match
  case Seq()                          => "no command"
  case Seq("help")                    => "showing help"
  case Seq("add", a, b)               => s"sum = ${a.toInt + b.toInt}"
  case Seq("echo", words*)            => words.mkString(" ")
  case Seq(first, _*)                 => s"unknown command: $first"

@main def run(): Unit =
  println(parse(Seq()))
  println(parse(Seq("help")))
  println(parse(Seq("add", "4", "38")))
  println(parse(Seq("echo", "hello", "pattern", "world")))
  println(parse(Seq("jump", "high")))
no command
showing help
sum = 42
hello pattern world
unknown command: jump

Constants, variables and backticks

A lowercase name in a pattern is a new variable that matches anything. To compare against an existing value instead, put the name in backticks (or use an uppercase constant).

scala · try it yourself
@main def run(): Unit =
  val expected = "admin"
  def check(role: String) = role match
    case `expected` => "full access"
    case "guest"    => "read only"
    case other      => s"no access for $other"
  println(check("admin"))
  println(check("guest"))
  println(check("intern"))
full access
read only
no access for intern

Without backticks, case expected => would match every role and shadow the outer value — a classic bug.

Typed patterns and union types

scala · try it yourself
def render(value: Int | String | Boolean | List[Int]): String = value match
  case 0                => "zero"
  case n: Int           => s"number $n"
  case s: String        => s"text '$s'"
  case true             => "yes"
  case false            => "no"
  case xs: List[Int]    => s"${xs.size} numbers"

@main def run(): Unit =
  List[Int | String | Boolean | List[Int]](0, 7, "hi", true, List(1, 2, 3))
    .map(render)
    .foreach(println)
zero
number 7
text 'hi'
yes
3 numbers

Int | String | … is a Scala 3 union type: the value is one of those types. Matching recovers which one.

Note: Generic type arguments are erased at run time on the JVM, so case xs: List[Int] really checks only "is it a List". It is safe here because the union type guarantees the element type.

Custom extractors

Any object with an unapply method can be used as a pattern. This lets you match on derived information.

scala · try it yourself
object Even:
  def unapply(n: Int): Boolean = n % 2 == 0

object Email:
  def unapply(s: String): Option[(String, String)] =
    s.split("@") match
      case Array(user, domain) if user.nonEmpty && domain.contains(".") => Some((user, domain))
      case _ => None

@main def run(): Unit =
  for n <- List(4, 7) do
    n match
      case Even() => println(s"$n is even")
      case _      => println(s"$n is odd")

  for s <- List("lin@shop.io", "broken@", "x@y") do
    s match
      case Email(user, domain) => println(s"user=$user domain=$domain")
      case _                   => println(s"'$s' is not an email")
4 is even
7 is odd
user=lin domain=shop.io
'broken@' is not an email
'x@y' is not an email

Even returns a Boolean, so it is used with empty parentheses: Even(). Email returns Option[(String, String)]: Some means "matched, and here are the parts", None means "no match".

Patterns outside match

Patterns also work in val definitions, for generators and lambdas with case:

scala · try it yourself
case class Score(player: String, points: Int)

@main def run(): Unit =
  val Score(who, pts) = Score("Uma", 88)
  println(s"$who scored $pts")

  val scores = List(Score("Uma", 88), Score("Ravi", 95), Score("Jo", 71))
  for Score(name, p) <- scores if p > 80 do println(name)

  val labels = scores.map { case Score(n, p) => s"$n:$p" }
  println(labels)
  val (high, low) = scores.partition(_.points >= 80)
  println((high.map(_.player), low.map(_.player)))
Uma scored 88
Uma
Ravi
List(Uma:88, Ravi:95, Jo:71)
(List(Uma, Ravi),List(Jo))

Pattern reference

Pattern Example
literal case 0, case "yes"
variable / wildcard case x, case _
stable identifier case `expected`
typed case s: String
alternatives case 'a' | 'e'
tuple case (a, b)
constructor / extractor case Item(n, p), case Email(u, d)
sequence case List(a, b), case Seq(x, rest*)
binder case all @ Item(_, _)
guard case n if n > 0

Test yourself

In case Seq("echo", words*), what is words?

  1. The first word only
  2. All remaining elements after "echo"
  3. A String
  4. It does not compile

Why write `case expected =>` with backticks?

  1. To ignore the value
  2. To compare against the existing value expected instead of binding a new variable
  3. To make the match faster
  4. Backticks are required for all strings

What must an object provide to be usable as a pattern like case Email(u, d)?

  1. An apply method
  2. An unapply method
  3. A match method
  4. A toString method