Skip to content
Scala

Case Classes

Immutable data classes with auto-generated equals/hashCode/toString.

By EZ4Code Team
case-classdataimmutable

Code

case class Point(x: Double, y: Double)

val p1 = Point(1.0, 2.0)
val p2 = Point(1.0, 2.0)

// Auto-generated equality
p1 == p2  // true

// Auto-generated copy with changes
val p3 = p1.copy(y = 5.0)  // Point(1.0, 5.0)

// Destructure in pattern matching
p1 match {
  case Point(x, y) => s"($x, $y)"
}

Explanation

Case classes are Scala's idiomatic way to model immutable data. The compiler generates equals, hashCode, toString, a companion with apply/unapply, and a copy method for free. They enable pattern matching and are the foundation of algebraic data types.

More Scala Snippets