Scala 中的最终类和密封类有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32199989/
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
What are the differences between final class and sealed class in Scala?
提问by dcastro
There are two types of modifiers in Scala: finaland sealed
Scala 中有两种类型的修饰符:final和sealed
What are the differences between them? When should you use one over the other?
它们之间有什么区别?什么时候应该使用一个?
回答by dcastro
A finalclass cannot be extended, period.
一个final班级不能延期,期间。
A sealedtrait can only be extended in the same source fileas it's declared. This is useful for creating ADTs (algebraic data types). An ADT is defined by the sumof its derived types.
一个sealed特质只能在同一中扩展源文件,因为它的声明。这对于创建 ADT(代数数据类型)很有用。ADT由其派生类型的总和定义。
E.g.:
例如:
- An
Option[A]is defined bySome[A]+None. - A
List[A]is defined by::+Nil.
- An
Option[A]由Some[A]+定义None。 - A
List[A]由::+定义Nil。
sealed trait Option[+A]
final case class Some[+A] extends Option[A]
object None extends Option[Nothing]
Because Option[A]is sealed, it cannot be extended by other developers - doing so would alter its meaning.
因为Option[A]是密封的,它不能被其他开发者扩展——这样做会改变它的含义。
Some[A]is final because it cannot be extended, period.
Some[A]是最终的,因为它不能延长,期限。
As an added bonus, if a trait is sealed, the compiler can warn you if your pattern matches are not exhaustive enough because it knowsthat Optionis limitedto Someand None.
作为额外的奖励,如果一个特点是密封的,编译器可以警告你,如果你的模式匹配的并不详尽不够,因为它知道这Option是限制于Some和None。
opt match {
case Some(a) => "hello"
}
Warning: match may not be exhaustive. It would fail on the following input:
None
警告:匹配可能并不详尽。它会在以下输入上失败:
None
回答by agschaid
sealedclasses (or traits) can still be inherited in the same source file (where finalclasses can't be inherited at all).
sealed类(或特征)仍然可以在同一个源文件中final被继承(类根本不能被继承)。
Use sealedwhen you want to restrict the number of subclasses of a base class (see "Algebraic Data Type").
sealed当您想要限制基类的子类数量时使用(请参阅“代数数据类型”)。
As one of the very practical benefits of such a restriction the compiler can now warn you about non-exaustive pattern matches:
作为这种限制的非常实用的好处之一,编译器现在可以警告您非详尽的模式匹配:
sealed trait Duo
case class One(i:Int) extends Duo
case class Two(i:Int, j:Int) extends Duo
def test(d:Duo) {
match {
case One(x) => println(x) // warning since you are not matching Two
}
}

