2

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())    
  }
}
GA1
  • 1,568
  • 2
  • 19
  • 30

1 Answers1

1

You can use with

trait C {
 self: A with B =>
}
Nagarjuna Pamu
  • 14,737
  • 3
  • 22
  • 40
  • Could you explain why did you use `self` instead of my `this`? – GA1 Sep 15 '16 at 14:13
  • 1
    @GA1 `this` is used to refer to current object in context. used self just for the sake of clarity . – Nagarjuna Pamu Sep 15 '16 at 14:17
  • 1
    `this` should be used in this context, since there's no reason to introduce another self-type reference. Alternative self-type reference is used when you need to distinguish between different `this` instances, particularly in case of nested classes. – Haspemulator Sep 15 '16 at 14:33