Nested Patterns
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: