模式匹配密封特征

当模式匹配类型为密封特征的对象时,Scala 将在编译时检查所有情况是否穷举匹配

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.
}

如果稍后添加了 Shape 的新 case class,则 Shape 上的所有 match 语句将开始抛出编译器警告。这使得彻底的重构更容易:编译器将提醒开发人员需要更新的所有代码。