Matching Tuples
In this page:
Matching Tuples
A pattern like case (a, b) => destructures a tuple directly into its component parts inside a match branch, binding each part to a new variable. This works for tuples of any size and can be combined with type or literal patterns on individual components. It's a much more direct way to work with tuple contents than repeatedly calling ._1, ._2.
Note: Tuple patterns can mix literal values and variable bindings, like case (0, y) => ... to match only when the first element is exactly 0.
Example: Matching Tuples
object Main extends App {
val point = (3, 4)
val description = point match {
case (0, 0) => "origin"
case (x, 0) => s"on the x-axis at $x"
case (0, y) => s"on the y-axis at $y"
case (x, y) => s"at ($x, $y)"
}
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: