Matching Case Classes
Matching case classes peeks inside an object and pulls out its fields as you check its kind. It is like opening a toy box and reading the labels on each item.
In this page:
Syntax
value match {
case ClassName(field1, field2) => expression
case OtherClass(field) => expression
}
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
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
- Using a plain class instead of a
case classand expectingcase Point(x, y)to work, since a plain class has nounapply. - Writing the wrong number of fields in the pattern, such as
case Point(x)for a two-field class. - Assuming pattern variables are
var, when they are newvalbindings only for that case.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: