我发现 Scala 中的特征与 Java 中的接口(interface)类似(但是 Java 中的接口(interface)扩展了其他接口(interface),它们不扩展类)。我看到an example on SO about traits usage其中特征扩展了类。
这样做的目的是什么?为什么特征可以扩展类?
最佳答案
是的,可以,扩展类
的特征
对哪些类
可以扩展该特征
施加了限制> - 也就是说,所有混合该特征
的类
必须扩展该类
。
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
^
关于scala - 为什么 Scala Trait 可以扩展类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12854941/