使用覆盖来堆叠特征和抽象类

Ian*_*Ian 0 scala

让我说我有以下代码,我允许混合生物,因为有人可以混合和匹配物种(例如,只有纯人类或纯外星人),我想有一个方法,解释什么是'混入',这是叫say:

trait Person {

  def say(): Unit

}

trait Human {

  def say(): Unit = println("Hi, I am a human")
}

trait Dude extends Human {

  override def say(): Unit = {
    super.say()
    println("Duuude!")
  }
}

abstract class Alien(msg: String) extends Person {

  def say(): Unit = println(s"Hi, I'm an alien: $msg")
}

class Hybrid(name: String) extends Alien("bleep") with Dude // does not work!

val someone = new Hybrid("John")
someone.say()
Run Code Online (Sandbox Code Playgroud)

这不能编译,因为:

error: overriding method say in class Alien of type ()Unit;
method say in trait Dude of type ()Unit cannot override a concrete member without a third member that's overridden by both (...)
Run Code Online (Sandbox Code Playgroud)

是否有可能让someone.say()显示以下内容?

Hi, I'm am a human
Duuude!
Hi, I'm an alien: bleep
Run Code Online (Sandbox Code Playgroud)

我曾经想过创建已混入两个性状/班一类特殊的,但我怎么会那么去访问相应的say方法,因为很明显super.say将是不明确的.

Ale*_*nov 6

class Hybrid(name: String) extends Alien("bleep") with Dude {
  override def say() = {
    super[Dude].say()
    super[Alien].say()
  }
}
Run Code Online (Sandbox Code Playgroud)