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

Nested Patterns

Nested patterns look inside things that sit inside other things, like checking a box inside a box. You can match a deep detail in one neat line.

In this page:

  1. Nested Patterns
Syntax
scala
value match {
  case Some(ClassName(a, b)) => expression
  case _                     => default_result
}

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing case Some(Point(0, 0)) on an Option[Line], which has the wrong nested type.
  2. Nesting patterns so deep that the code becomes unreadable, when a helper variable with @ could help.
  3. Forgetting the None case, so the match is non-exhaustive.
🔒

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.