← Back to Scala Course | Chapter 10: Pattern Matching | Lesson 6 of 7

Nested Patterns

In this page:

  1. Nested Patterns

Nested Patterns

Patterns can nest inside each other, like case Some(Point(0, 0)) =>, matching deeply into a structure's shape in a single case. This lets a single pattern express conditions that would otherwise require several separate nested if/match statements. Nested patterns are especially powerful combined with case classes and standard types like Option and List.

Note: Nested patterns let you match arbitrarily deep structure in one case, avoiding a pyramid of nested match/if statements.

Example: Nested Patterns

markup
case class Point(x: Int, y: Int)
case class Line(start: Point, end: Point)

object Main extends App {
  val line = Line(Point(0, 0), Point(5, 5))

  val description = line match {
    case Line(Point(0, 0), Point(x, y)) => s"starts at origin, ends at ($x, $y)"
    case Line(a, b) => s"from $a to $b"
  }

  println(description)
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.