Scala Language Pattern Matching Pattern Matching Sealed Traits


When pattern matching an object whose type is a sealed trait, Scala will check at compile-time that all cases are 'exhaustively matched':

sealed trait Shape
case class Square(height: Int, width: Int) extends Shape
case class Circle(radius: Int) extends Shape
case object Point extends Shape

def matchShape(shape: Shape): String = shape match {
    case Square(height, width) => "It's a square"
    case Circle(radius)        => "It's a circle"
    //no case for Point because it would cause a compiler warning.

If a new case class for Shape is later added, all match statements on Shape will start to throw a compiler warning. This makes thorough refactoring easier: the compiler will alert the developer to all code that needs to be updated.