Scala Language Pattern Matching Pattern Matching Sealed Traits

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any Scala Language Question?