如何强制特质实现另一个特征

时间:2016-09-15 14:06:17

标签: scala multiple-inheritance mixins traits

我有三个特征,我想强迫其中一个人称之为C以混合特征AB。即使我知道如何强制B混合A,我也无法做到。可以这样做:

trait A {
  def getThree() = 3
}

trait B {
  this: A =>
  def getFive() = 2 + getThree()
}

trait C {
  this: A => // that's the line which 
  // this: B => // this line is incorrect as I there is "this: A =>" already
  // def getEight() = getThree() + getFive() // I want this line to compile
}

因此我可以调用函数getEight()

object App {
  def main(args: Array[String]): Unit = {

    val b = new B with A {}
    println(b.getFive())

    // It would be cool to make these two lines work as well
    // val c = new C with B with A {}
    // println(c.getEight())    
  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用with

trait C {
 self: A with B =>
}