我们来看下面的例子 trait Drawable { def draw def paint}trait Cowboy extends Drawable { override def draw() { println("Bang!") } override def paint(){ println("I need this to be painted")}}trait Artist extends Drawable { override de
trait Drawable { def draw def paint } trait Cowboy extends Drawable { override def draw() { println("Bang!") } override def paint(){ println("I need this to be painted")} } trait Artist extends Drawable { override def draw() { println("A pretty painting") } override def paint(){ println("I don't want this to be painted")} } class CowboyArtist extends Cowboy with Artist object Main extends App { (new CowboyArtist()).draw() // A pretty painting (new CowboyArtist()).paint() // I don't want this to be painted }
在这里,Artist和Cowboy继承了Drawable并覆盖了draw和paint方法. CowboyArtist以同样的顺序继承了Cowboy和Artist.根据我的read,scala根据其继承的顺序和最右边特征的方法执行来确定要调用的方法.
但是,如果我想要从一个特征中调用其中一个方法,另一个方法来自另一个特征,如你所见,我希望从Artist特征执行draw方法,但我希望从牛仔的特质.
这可能吗?如果不是什么是解决方法?
当然,只需使用:class CowboyArtist extends Cowboy with Artist { override def paint = super[Cowboy].paint }
super [Trait]允许您从要调用的线性化中选择确切的特征.
所以现在:
scala> (new CowboyArtist()).paint() I need this to be painted scala> (new CowboyArtist()).draw() A pretty painting
附:你也可以在内部特征中使用super [Trait],这样你就可以在将它混合到类之前创建一个具有正确优先级的mixin:
trait CowboyArtistMixin extends Cowboy with Artist{ override def paint = super[Cowboy].paint } class CowboyArtist extends CowboyArtistMixin