Skip to content
Case Classes and Sealed Traits
step 1/5

Reading — step 1 of 5

Learn

~1 min readPattern Matching

Case classes are immutable data carriers with auto-generated equality, hashCode, toString, and copy:

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

val p = Point(3, 4)              // no `new` needed
p.x                              // 3
p == Point(3, 4)                 // true (structural equality)
val moved = p.copy(x = 10)       // Point(10, 4)

Sealed traits restrict who can extend them — all subclasses must be in the same file. Combined with case classes, this enables exhaustive pattern matching:

sealed trait Shape
case class Circle(radius: Double) extends Shape
case class Square(side: Double) extends Shape
case class Rectangle(w: Double, h: Double) extends Shape

def area(s: Shape): Double = s match {
  case Circle(r)       => math.Pi * r * r
  case Square(s)       => s * s
  case Rectangle(w, h) => w * h
}

The compiler warns if you forget a case. This is the classic ADT (algebraic data type) pattern from functional programming.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…