Scala 中的最终类和密封类有什么区别? [英] What are the differences between final class and sealed class in Scala?
问题描述
Scala 中有两种修饰符:final
和 sealed
它们之间有什么区别?什么时候应该使用一个?
final
类不能扩展,句号.
sealed
trait 只能在与声明相同的源文件中扩展.这对于创建 ADT(代数数据类型)很有用.ADT 由其派生类型的sum定义.
例如:
Option[A]
由Some[A]
+None
定义.- A
List[A]
由::
+Nil
定义.
密封特性选项[+A]最终案例类 Some[+A] 扩展 Option[A]对象无扩展选项[Nothing]
因为 Option[A]
是密封的,其他开发者无法对其进行扩展 - 这样做会改变其含义.
Some[A]
是最终的,因为它不能被延长,期间.
作为一个额外的好处,如果一个特征被密封,如果你的模式匹配不够详尽,编译器会警告你,因为它知道Option
是限制为Some
和None
.
选择匹配{case Some(a) =>你好"}
<块引用>
警告:匹配可能并不详尽.它会在以下输入上失败:None
There are two types of modifiers in Scala: final
and sealed
What are the differences between them? When should you use one over the other?
A final
class cannot be extended, period.
A sealed
trait can only be extended in the same source file as it's declared. This is useful for creating ADTs (algebraic data types). An ADT is defined by the sum of its derived types.
E.g.:
- An
Option[A]
is defined bySome[A]
+None
. - A
List[A]
is defined by::
+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.
Some[A]
is final because it cannot be extended, period.
As an added bonus, if a trait is sealed, the compiler can warn you if your pattern matches are not exhaustive enough because it knows that Option
is limited to Some
and None
.
opt match {
case Some(a) => "hello"
}
Warning: match may not be exhaustive. It would fail on the following input:
None
这篇关于Scala 中的最终类和密封类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!