为什么Scala特性可以扩展一个类?

Raj*_*Raj 53 scala traits

我看到Scala中的特性与Java中的接口类似(但Java中的接口扩展了其他接口,它们不扩展类).我在SO上看到了一个关于特征使用的例子,其中特征扩展了一个类.

这样做的目的是什么?为什么traits可以扩展类?

ade*_*rtc 69

是的,他们可以,一个trait扩展的class东西限制了classes可以扩展的东西trait- 即所有必须扩展的classes混合.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
                              ^
Run Code Online (Sandbox Code Playgroud)

  • 有趣.但是你也可以通过在自我类型上放置一个类型约束来限制可以混合特征的类,例如`trait FooTrait {self:Foo =>}`.你什么时候使用一种技术而不是另一种? (14认同)
  • @AmigoNico [here](http://stackoverflow.com/q/36945333/2032064)是您可能更喜欢从类继承的一个示例. (3认同)