声明为 sealed 的 trait 只能被同一个文件内的 class 继承。sealed 关键字可以方便 scala 编程中模式匹配方法的使用,使用 sealed 关键字修饰的 trait 和相应的被 case 修饰的子类,类似其他语言中的 enums 类型的作用。由于 sealed trait 的所有子类都被封装在一个文件中,编译器就可以知道该 trait 的所有子类,从而在进行模式匹配时进行检查。如果程序员在编写 match { case } 代码时没有枚举到所有类型的话,编译器会报告“没有匹配尽所有情况(match is not exhaustive)”的警告。例如:
代码来自 https://stackoverflow.com/questions/11203268/what-is-a-sealed-trait
sealed trait Answer
case object Yes extends Answer
case object No extends Answer
如果在 match { case } 代码块中没有匹配尽所有情况,
scala> val x: Answer = Yes
x: Answer = Yes
scala> x match {
| case No => println("No")
| }
<console>:12: warning: match is not exhaustive!
missing combination Yes