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

How to force a trait to implement another 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())    
  }
}

您可以使用with

trait C {
 self: A with B =>
}