Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Case Classes and Pattern Matching

Scala Extractors and Advanced Patterns

Go beyond basic matching in Scala 3: write custom extractors with unapply and unapplySeq, match regular expressions, and use partial functions and collect.

Case classes support pattern matching out of the box, but patterns are not limited to them. Any object with a method called unapply can be used in a pattern. These extractors let you match on strings, numbers, regular expressions, or any computed view of your data, while keeping match expressions short and readable.

This lesson also covers partial functions, which are the bridge between pattern matching and collection operations such as collect.

How patterns call unapply

When you write case Point(x, y), the compiler calls Point.unapply(value). For a case class that method is generated. If it returns something that means "success with these values", the pattern matches and x and y are bound.

You can write your own:

SCALA
object Even:
  def unapply(n: Int): Boolean = n % 2 == 0

def parity(n: Int): String = n match
  case Even() => "even"
  case _ => "odd"

println(parity(10))  // even
println(parity(7))   // odd

A boolean extractor (unapply returning Boolean) acts as a named test. The empty parentheses Even() are required in the pattern.

To extract values, return an Option:

SCALA
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

def describe(s: String): String = s match
  case Email(user, domain) => s"user=$user, domain=$domain"
  case _ => "not an email"

println(describe("[email protected]"))  // user=ann, domain=example.com
println(describe("hello"))            // not an email

Some((user, domain)) means the extractor produces two values. If it returned None, the pattern would fail and matching would continue with the next case. In Scala 3 you may return any type with isEmpty and get, but Option is the common choice.

How an extractor runs

Pattern appears case Email(u, d)
unapply is called Email.unapply(value)
Some or None Some binds u and d. None tries the next case.
1 / 2

Sequence extractors: unapplySeq

When the number of extracted values varies, implement unapplySeq. That is how List(a, b, _*) and Array(x, y) patterns work.

SCALA
object Words:
  def unapplySeq(s: String): Option[Seq[String]] =
    val parts = s.trim.split("\\s+").toSeq
    if s.trim.isEmpty then None else Some(parts)

def summary(s: String): String = s match
  case Words(only) => s"one word: $only"
  case Words(first, second) => s"two words: $first and $second"
  case Words(first, _*) => s"starts with $first"
  case _ => "blank"

println(summary("hello"))            // one word: hello
println(summary("big dog"))          // two words: big and dog
println(summary("a b c d"))          // starts with a

The _* wildcard matches "any remaining elements" and must be last.

Regular expressions as patterns

A scala.util.matching.Regex has an unapplySeq that returns the capture groups. This makes parsing short and clear:

SCALA
val Date = """(\d{4})-(\d{2})-(\d{2})""".r
val Duration = """(\d+)(ms|s|min)""".r

def parse(input: String): String = input match
  case Date(year, month, day) => s"date: $day/$month/$year"
  case Duration(amount, unit) => s"duration: $amount $unit"
  case _ => "unknown format"

println(parse("2025-03-14"))  // date: 14/03/2025
println(parse("250ms"))       // duration: 250 ms

Notes:

  • The match must cover the entire string. "2025-03-14 extra" would not match Date.
  • Triple-quoted strings ("""...""") keep backslashes literal, so you do not need to double them.
  • The captured values are always Strings; convert them yourself (year.toInt).
  • For a search anywhere in text, use Date.findFirstIn(text) or .findAllMatchIn(text) instead.

Pattern-based helper extractors

Extractors are a good way to add meaning to raw values without changing their type. For example, parsing integers inside a match:

SCALA
object AsInt:
  def unapply(s: String): Option[Int] = s.toIntOption

def add(a: String, b: String): String = (a, b) match
  case (AsInt(x), AsInt(y)) => s"sum is ${x + y}"
  case (AsInt(_), _) => s"second value is not a number: $b"
  case _ => s"first value is not a number: $a"

println(add("4", "38"))   // sum is 42
println(add("4", "x"))    // second value is not a number: x

Patterns compose: (AsInt(x), AsInt(y)) runs two extractors inside a tuple pattern.

Matching with val, for and catch

Destructuring works wherever a pattern is allowed:

SCALA
val (name, age) = ("Zoe", 7)
case class Point(x: Int, y: Int)
val Point(px, py) = Point(1, 2)   // a case class pattern that cannot fail

val pairs = List(("a", 1), ("b", 2), ("c", 3))
for (letter, number) <- pairs do println(s"$letter -> $number")

In a for over a collection, a pattern that can fail acts as a filter in Scala 3 when you write case explicitly: for case Some(x) <- listOfOptions yield x keeps only the Some values. Without case, Scala 3 warns if the pattern is refutable.

SCALA
val results = List(Some(1), None, Some(3))
val values = for case Some(x) <- results yield x * 10
println(values)   // List(10, 30)

Partial functions

A partial function is a function defined only for some inputs. In Scala it is written as a case block and has the type PartialFunction[A, B]. It has two key methods: isDefinedAt tests whether it applies and apply runs it.

SCALA
val smallToWord: PartialFunction[Int, String] = {
  case 1 => "one"
  case 2 => "two"
  case 3 => "three"
}

println(smallToWord.isDefinedAt(2))   // true
println(smallToWord.isDefinedAt(9))   // false
println(smallToWord.lift(9))          // None
println(smallToWord.lift(1))          // Some(one)

Calling smallToWord(9) throws a MatchError. lift converts it into a total function that returns an Option.

The most useful application is collect, which filters and maps in one step:

SCALA
val mixed: List[Any] = List(1, "two", 3.0, 4, "five")
val ints = mixed.collect { case n: Int => n * 2 }
val lengths = mixed.collect { case s: String => s.length }
println(ints)     // List(2, 8)
println(lengths)  // List(3, 4)

collect skips the elements for which the partial function is not defined. You can chain partial functions with orElse:

SCALA
val handleNumbers: PartialFunction[Any, String] = { case n: Int => s"int $n" }
val handleText: PartialFunction[Any, String] = { case s: String => s"text $s" }
val handler = handleNumbers.orElse(handleText).orElse { case _ => "other" }
println(handler(5))      // int 5
println(handler("hi"))   // text hi
println(handler(2.5))    // other

This is also the idea behind event handlers in actor systems and routers in web frameworks, where each handler matches the messages it understands.

The same ideas on the JVM

The Java and Kotlin examples below are not Scala. They show the shared concepts: a regex with capture groups, and an "extractor" implemented as a function that returns an optional result.

Java Java: regex groups and Optional as an extractor (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: regex destructuring and mapNotNull (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

  • Expecting a regex pattern to find text inside a string. It must match all of it.
  • Forgetting () for a boolean extractor (case Even => refers to the object itself).
  • Heavy work inside unapply. Extractors may run for every case in order; keep them cheap or cache the result.
  • Calling a partial function directly without isDefinedAt or lift, which can throw MatchError.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the compiler call when it evaluates case Email(u, d)?

    Patterns use unapply (or unapplySeq). apply is for construction.
  2. 2. Which method should you implement for a pattern like case Words(first, _*)?

    unapplySeq returns a sequence of values of unknown length, which is what the _* wildcard needs.
  3. 3. What does List(1, "a", 2).collect { case n: Int => n * 10 } return?

    collect applies the partial function only where it is defined and drops the other elements.
  4. 4. What does pf.lift(x) do for a partial function that is not defined at x?

    lift turns a PartialFunction[A, B] into A => Option[B].

Summary

  • Any object with unapply (or unapplySeq) can be used in a pattern; return Boolean, Option or Option of a tuple.
  • Regular expressions work as patterns and bind capture groups as strings, matching the whole input.
  • Patterns can appear in val, for (with case) and catch.
  • A PartialFunction is a case block defined for some inputs: use isDefinedAt, lift, orElse and collect.

Next: Immutability and Pure Functions