Start Coding

Topics

Scala Sealed Traits

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.

What are Sealed Traits?

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.

Syntax and Usage

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.

Benefits of Sealed Traits

  • Exhaustive pattern matching
  • Improved type safety
  • Better code organization
  • Compiler warnings for non-exhaustive matches

Pattern Matching with Sealed Traits

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.

Use Cases

Sealed traits are particularly useful for:

  • Representing algebraic data types
  • Modeling domain-specific languages
  • Implementing state machines
  • Defining error hierarchies

Best Practices

  • Use sealed traits for finite hierarchies
  • Combine with case classes for immutable data modeling
  • Leverage pattern matching for type-safe operations
  • Consider sealed abstract classes for hierarchies with common implementations

Sealed Traits vs. Enums

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.

Conclusion

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.