Matching Case Classes
In this page:
Matching Case Classes
Case classes support pattern matching directly on their fields, like case Point(x, y) =>, destructuring an instance into its constructor parameters within the branch, without calling ._1-style accessors. This works because case classes automatically generate an unapply method that pattern matching relies on behind the scenes. It's one of the biggest reasons case classes are preferred for data modeling in idiomatic Scala.
Note: Pattern matching on case classes relies on the automatically-generated unapply method -- this is exactly why case classes support it and plain classes don't, by default.
Example: Matching Case Classes
case class Point(x: Int, y: Int)
object Main extends App {
val p = Point(3, 4)
val description = p match {
case Point(0, 0) => "origin"
case Point(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: