模式匹配密封特徵

當模式匹配型別為密封特徵的物件時,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 語句將開始丟擲編譯器警告。這使得徹底的重構更容易:編譯器將提醒開發人員需要更新的所有程式碼。