我看到,在Scala的特征类似于在Java接口(Java编写,但接口扩展其它接口,它们并不扩展类)。 我看到的SO约特质用法的例子 ,其中一个特征扩展一个类。
这样做的目的是什么? 为什么性状扩展类?
我看到,在Scala的特征类似于在Java接口(Java编写,但接口扩展其它接口,它们并不扩展类)。 我看到的SO约特质用法的例子 ,其中一个特征扩展一个类。
这样做的目的是什么? 为什么性状扩展类?
是的,他们可以,一个trait
是延伸的class
穿什么限制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
^