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:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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
- Writing
case Some(Point(0, 0))on anOption[Line], which has the wrong nested type. - Nesting patterns so deep that the code becomes unreadable, when a helper variable with
@could help. - Forgetting the
Nonecase, so the match is non-exhaustive.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: