简体   繁体   English

Scala中的密封特征和抽象密封类之间的具体区别是什么?

[英]What is the specific difference between a sealed trait and an abstract sealed class in scala?

I am looking to define the following algebraic data type in scala: 我想在scala中定义以下代数数据类型:

sealed trait Beat
case object Rest extends Beat
case object Hit extends Beat

Is there any difference, if I were to define this instead as: 有什么区别吗,如果我将其定义为:

abstract sealed class Beat
case object Rest extends Beat
case object Hit extends Beat

ie using an abstract sealed class instead of a trait? 即使用抽象的密封类而不是特征? The definitions appear to be equivalent. 这些定义似乎是等效的。

There is no difference in the meaning of sealed whether you put it on an (abstract) class or a trait. 无论将其放在(抽象的)类还是特质上,“密封”的含义没有区别。 So in your case, the two examples are indeed (almost) equivalent. 因此,在您的情况下,这两个示例确实(几乎)等效。

A difference between an abstract class and a trait comes apparent when a subclass wants to inherit from another class: A class/trait can always only extend a single class, but multiple traits. 当子类想从另一个类继承时,抽象类和特征之间的区别就很明显:一个类/特征总是只能扩展一个类,但是可以扩展多个特征。 For example: 例如:

class SomeClass

sealed trait Beat1
abstract sealed class Beat2

case object Rest1 extends SomeClass with Beat1 // ok
case object Rest2 extends SomeClass with Beat2 // compile error

Otherwise, an abstract class and a trait are pretty much equivalent. 否则,抽象类和特征几乎是等效的。 The biggest differences in practice probably only appear once you are concerned about binary compatibility (kind of out of scope for this answer). 实际上,最大的差异可能仅在您担心二进制兼容性时才会出现(这种答案超出了范围)。

To add to gzm0's answer , a further difference between an abstract sealed class and a trait is that an abstract sealed class, like any other class but unlike a trait, can have constructor parameters: 为了增加gzm0的答案 ,抽象密封类和trait之间的另一个区别是,抽象密封类与其他任何类一样,但与trait不同,可以具有构造函数参数:

abstract sealed class Duck(sound: String)

case object RealDuck extends Duck("quack")
case object RubberDuck extends Duck("squeak")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM