Scala 的密封抽象与抽象类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3032771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala's sealed abstract vs abstract class
提问by ?ukasz Lew
What is the difference between sealed abstractand abstractScala class?
sealed abstract和abstractScala类有什么区别?
回答by sepp2k
The difference is that all subclasses of a sealed class (whether it's abstract or not) must be in the same file as the sealed class.
区别在于密封类的所有子类(无论是否抽象)都必须与密封类在同一个文件中。
回答by Daniel C. Sobral
As answered, all directly inheritingsubclasses of a sealed class (abstract or not) must be in the same file. A practical consequence of this is that the compiler can warn if the pattern match is incomplete. For instance:
正如回答的那样,密封类(抽象或非抽象)的所有直接继承子类必须在同一个文件中。这样做的一个实际结果是,如果模式匹配不完整,编译器会发出警告。例如:
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
}
If the Treeis sealed, then the compiler warns unless that last line is uncommented.
如果Tree是sealed,则编译器会发出警告,除非最后一行未注释。

