如何在声明一个类时使用mixin

时间:2018-02-17 12:30:52

标签: scala

假设我使用mixin如下:

trait A {
    def foo: String
}

class B extends A {
    def foo = "B"
}

class C extends A {
    def foo = "C"
}

trait MixIn extends A {
    abstract override def foo = super.foo + " with MixIn"
}

val c = new C with MixIn

我有一个场景,我想在声明一个类而不是实例时使用mixin。但是当我尝试以下操作时出现编译错误:

class D extends A with MixIn {
    def foo = "D"
}
  

方法foo需要`override'修饰符

在这种情况下使用mixin的合适方法是什么?

1 个答案:

答案 0 :(得分:0)

你快到了

trait A {
  def foo: String
}
trait MixIn extends A {
  abstract override def foo = super.foo + " with MixIn"
}
abstract class beforeD extends A {
  override def foo = "D"
}
class D extends beforeD with MixIn

你只需要foo的具体抽象实现,它将从MixIn

中调用为super.foo

更新为动物案例

abstract class LikeDog extends Animal {
  override def whoAmI: String = "I'm a dog"
}

class Dog extends LikeDog with Domestic