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

时间:2016-09-01 09:20:28

标签: 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()

这不能编译,因为:

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 (...)

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

Hi, I'm am a human
Duuude!
Hi, I'm an alien: bleep

我已经考虑创建一个已经混合了两个特征/类的特殊类,但是我将如何访问相应的say方法,因为显然super.say将是不明确的。

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:0)

所以基本上类Hybrid不知道哪个方法需要被覆盖。这可以通过更改方法名称来解决。你可以尝试这个

trait Person {

  def say(): String

 }

  trait Human {
  def sayHuman: String = ("Hi, I am a human")
 }

trait Dude extends Human {

 override def sayHuman(): String = {
super.sayHuman +"Duuude!"
 }
}

 abstract class Alien(msg: String) extends Person {

  def say(): String= "Hi, I'm an alien:"+msg
}


class Hybrid(name: String) extends Alien("bleep") with Dude{
override def toString:String= super.say+"\n"+super.sayHuman
}