Sealed traits are a powerful feature in Scala that enhance type safety and pattern matching. They provide a way to define a closed set of subtypes, ensuring that all possible implementations are known at compile-time.
A sealed trait is a trait that can only be extended by classes in the same file where it is defined. This restriction allows the compiler to know all possible subtypes of the trait, enabling exhaustive pattern matching and improved type checking.
To define a sealed trait, use the sealed
keyword before the trait
keyword:
sealed trait Shape
case class Circle(radius: Double) extends Shape
case class Rectangle(width: Double, height: Double) extends Shape
case class Triangle(base: Double, height: Double) extends Shape
In this example, Shape
is a sealed trait with three case classes extending it. All these definitions must be in the same file.
Sealed traits excel in pattern matching scenarios. The compiler can verify if all cases are covered:
def area(shape: Shape): Double = shape match {
case Circle(r) => Math.PI * r * r
case Rectangle(w, h) => w * h
case Triangle(b, h) => 0.5 * b * h
}
If you forget to handle a case, the compiler will warn you about non-exhaustive pattern matching.
Sealed traits are particularly useful for:
While similar to enums, sealed traits offer more flexibility. They can have complex subtypes and carry additional data, making them suitable for more sophisticated modeling scenarios.
Sealed traits are a cornerstone of Scala's type system, providing a powerful tool for creating closed type hierarchies. By leveraging sealed traits, developers can write more robust and type-safe code, especially when combined with pattern matching and case classes.