Scala Pattern Matching

Pattern matching is Scala's most powerful control flow.

Basic Matching

Scala
val x = 42
val description = x match {
  case 0 => "zero"
  case 1 => "one"
  case n if n > 0 => s"positive: $n"
  case _ => "negative"
}

Matching on Types

Scala
def describe(obj: Any): String = obj match {
  case s: String => s"String of length ${s.length}"
  case i: Int    => s"Integer: $i"
  case _         => "Unknown type"
}

Destructuring Case Classes

Scala
case class Point(x: Double, y: Double)
case class Circle(center: Point, radius: Double)

def area(shape: Any): Double = shape match {
  case Circle(Point(cx, cy), r) => math.Pi * r * r
  case _ => 0
}

Matching on Collections

Scala
val list = List(1, 2, 3)
list match {
  case head :: tail  => println(s"head: $head, tail: $tail")
  case Nil           => println("empty")
}

Tips

  • Pattern matching is exhaustive — the compiler warns if you miss cases.
  • Use case _ as a fallback to avoid MatchError.
  • Combine with sealed classes for compiler-checked exhaustiveness.

Next: futures.