我看到 Scala 中的特征类似于 Java 中的接口(但 Java 中的接口扩展了其他接口,它们不扩展类)。我在 SO 上看到了一个关于特征使用的示例,其中特征扩展了一个类。
这样做的目的是什么?为什么特质可以扩展类?
我看到 Scala 中的特征类似于 Java 中的接口(但 Java 中的接口扩展了其他接口,它们不扩展类)。我在 SO 上看到了一个关于特征使用的示例,其中特征扩展了一个类。
这样做的目的是什么?为什么特质可以扩展类?
是的,他们可以,trait扩展 a 的classa 限制了classes可以扩展的内容trait- 即,所有必须扩展 thatclasses的混入。traitclass
scala> class Foo
defined class Foo
scala> trait FooTrait extends Foo
defined trait FooTrait
scala> val good = new Foo with FooTrait
good: Foo with FooTrait = $anon$1@773d3f62
scala> class Bar
defined class Bar
scala> val bad = new Bar with FooTrait
<console>:10: error: illegal inheritance; superclass Bar
is not a subclass of the superclass Foo
of the mixin trait FooTrait
val bad = new Bar with FooTrait
^