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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12854941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:36:55  来源:igfitidea点击:

Why can a Scala trait extend a class?

scalatraits

提问by Raj

I see that traits in Scala are similar to interfaces in Java (but interfaces in Java extend other interfaces, they don't extend a class). I saw an example on SO about traits usagewhere a trait extends a class.

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

What is the purpose of this? Why can traits extend classes?

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

回答by adelbertc

Yes they can, a traitthat extends a classputs a restriction on what classescan extend that trait- namely, all classesthat mix-in that traitmust extend that class.

是的,他们可以, atrait扩展 aclass限制了classes可以扩展它的内容trait- 即所有必须扩展 that 的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@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
                              ^