sep*_*p2k 83
不同之处在于密封类的所有子类(无论是否抽象)必须与密封类位于同一文件中.
Dan*_*ral 76
正如所回答的,所有直接继承密封类(抽象或非抽象)的子类必须在同一个文件中.这样做的一个实际结果是编译器可以警告模式匹配是否不完整.例如:
sealed abstract class Tree
case class Node(left: Tree, right: Tree) extends Tree
case class Leaf[T](value: T) extends Tree
case object Empty extends Tree
def dps(t: Tree): Unit = t match {
case Node(left, right) => dps(left); dps(right)
case Leaf(x) => println("Leaf "+x)
// case Empty => println("Empty") // Compiler warns here
}
Run Code Online (Sandbox Code Playgroud)
如果Tree
是sealed
,则编译器会发出警告,除非最后一行被取消注释.