【问题标题】:Why can a Scala trait extend a class?为什么 Scala trait 可以扩展一个类?
【发布时间】:2012-10-03 00:36:47
【问题描述】:

我看到 Scala 中的特征类似于 Java 中的接口(但 Java 中的接口扩展了其他接口,它们不扩展类)。我看到an example on SO about traits usage 的特征扩展了一个类。

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

【问题讨论】:

  • 如果您阅读链接的答案,您会发现特征与接口非常不同,因为它们可以包含实现。
  • 您可能还对 trait 继承和自类型注解的区别感兴趣:stackoverflow.com/questions/1990948/…
  • 是的,我理解了这一点,与接口不同,特征可以包含方法的部分实现,但我不确定特征扩展类的目的(如示例中所述)

标签: scala traits


【解决方案1】:

是的,他们可以,扩展 classtrait 限制了 classes 可以扩展 trait 的内容 - 即,所有 classes 混入 trait 必须扩展 @ 987654328@.

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
                              ^

【讨论】:

  • 有趣。但是您也可以通过对自身类型施加类型约束来限制可以混合特征的类,例如trait FooTrait { self:Foo =&gt; }。您什么时候使用一种技术而不是另一种?
  • Scala 对所有的打字业务都非常疯狂。我可以肯定地看到这可能非常有用,但是任何人都可以给出任何具体的例子吗?
  • @AmigoNico here 是您可能更喜欢从类继承的一个示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 1970-01-01
相关资源
最近更新 更多