Search code examples
scalamultiple-inheritancemixinstraits

How to force a trait to implement another traits


I have three traits, I would like to force one of them call it C to mix in the traits A and B. I can't do it even though I know how to force B to mix in A. It could be done like this:

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
}

Thus I could call the function 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())    
  }
}

Solution

  • You can use with

    trait C {
     self: A with B =>
    }