What are sealed traits and classes in Scala?
Answer
A sealed trait or class can only be extended within the same source file. This restricts the class hierarchy and enables the compiler to perform exhaustiveness checking on pattern matches. Classic ADT (Algebraic Data Type) pattern: sealed trait Shape; case class Circle(radius: Double) extends Shape; case class Rectangle(w: Double, h: Double) extends Shape. When you pattern match on a sealed type: shape match { case Circle(r) => ... } — the compiler warns if you don't handle all subtypes. This prevents bugs where new subtypes are added but existing match expressions aren't updated. Sealed hierarchies are the idiomatic Scala way to model closed sets of possibilities — like Rust's enums or Haskell's ADTs. They are used extensively for representing domain states, errors, and events.
Previous
What is the companion object in Scala?
Next
What is the difference between def, val, and lazy val for methods/values?