sealed abstract
和abstract
Scala类有什么区别?
不同之处在于,密封类的所有子类(无论是否为抽象类)都必须与密封类位于同一文件中。
如回答所述,所有直接继承密封类(抽象或非抽象)的子类必须在同一个文件中。这样做的实际后果是编译器可以在模式匹配不完整时发出警告。例如:
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
}
如果Tree
被sealed
,那么编译器会发出警告,除非最后一行被取消注释。
sealed
关键字。此时已经全部编译完成,包括match
语句。现在,另一个用户获取此jar文件并扩展Tree
。没有任何阻止他这样做的东西,但此时match
语句不再完整。由于他不是在编译它,只是从你的jar文件中使用它,编译器无法向他发出警告。而且,由于你在创建jar文件时不知道这一点,因此编译器也不能为你提供警告。 - Daniel C. Sobralsealed
关键字)之前,此时匹配语句还不完整,难道不是吗?这似乎很容易推断,因为即使没有新孩子(编译器还不知道它们),也没有‘Empty’分支。我谈到的是为创建jar文件的人提供警告,而不是使用它的人。 - sasha.sochka