Scala Case Classes and Pattern Matching
Define a data class and take it apart with match.
On this page
Scala functions.
- Define a data class and take it apart with match.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
A case class declares an immutable data type with generated helpers: you can create one without new, compare by value, and print it readably. Its fields are public vals.
match tests a value against patterns in order. case Point(0, 0) matches a literal, case Point(x, 0) matches any point on the x-axis and binds its x, and case _ is the catch-all.
Code example
object Main {
case class Point(x: Int, y: Int)
def describe(p: Point): String = p match {
case Point(0, 0) => "origin"
case Point(x, 0) => s"on x-axis at $x"
case _ => "elsewhere"
}
def main(args: Array[String]): Unit = {
println(describe(Point(0, 0)))
println(describe(Point(4, 0)))
println(describe(Point(1, 2)))
}
}origin on x-axis at 4 elsewhere
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
object Main { case class Point(x: Int, y: Int) def describe(p: Point): String = p match { case Point(0, 0) => "origin" case Point(x, 0) => s"on x-axis at $x" case _ => "elsewhere" } def main(args: Array[String]): Unit = { println(describe(Point(0, 0))) println(describe(Point(4, 0))) println(describe(Point(1, 2))) }}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| An immutable data type with matching support. | — | — | |
| The first pattern matches. | x = 0, y = 0 | origin | |
| The second pattern matches and binds x = 4. | x = 4, y = 0 | origin on x-axis at 4 | |
| Nothing earlier matches, so the catch-all runs. | x = 1, y = 2 | origin on x-axis at 4 elsewhere |
Behind the scenes
How Scala processes this code
Scala compiles for the JVM, which invokes the main entry point.
Cost and common mistakes
O(1) time and space per call.
- Patterns are tried in order, so a broad case placed first hides the later ones.
- Without a catch-all, an unmatched value throws a MatchError at runtime.
Try it yourself
Add a case for points on the y-axis.
Reveal answer and reasoning
Add case Point(0, y) => s"on y-axis at $y" before the catch-all.