我发现Scala中的特征类似于Java中的接口(但Java中的接口扩展了其他接口,它们不会扩展类)。我见过an example on SO about traits usage,其中一个特征扩展了一个类。
这样做的目的是什么?为什么特征可以扩展类?
发布于 2012-10-12 16:23:38
是的,扩展class
的trait
限制了哪些classes
可以扩展该trait
-即所有混合的classes
- trait
必须扩展该class
。
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
^
https://stackoverflow.com/questions/12854941
复制相似问题