Case Classes
In this page:
Case Classes
A case class automatically generates useful boilerplate: a companion object with apply, value-based equals/hashCode, a readable toString, and support for pattern matching. Case class fields are val by default, making instances immutable unless you explicitly mark a field var. Case classes are the idiomatic Scala way to model simple data-holding types.
Note: Case classes get pattern-matching support and value equality for free, making them the default choice for simple data models in Scala.
Example: Case Classes
case class Point(x: Int, y: Int)
object Main extends App {
val p1 = Point(1, 2)
val p2 = Point(1, 2)
println(p1)
println(p1 == p2) // value equality, not reference equality
val p3 = p1.copy(y = 99)
println(p3)
}
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: