user3663882 user3663882 - 3 months ago 20
Scala Question

Understanding DI in Scala

I have two traits:

trait A {
def a
}


And:

trait B { this: A =>
def b
}


Now, I tried to use
trait B
as this:

def method(bTrait: B) = bTrait.a //error


but it refuses to compile. I thought we could rely on that any implementations of
B
always extends
A
. What's wrong? Why doesn't it compile?

Answer

I thought we could rely on that any implementations of B always extends A

That's not what this: A => means. What it means is: "in order to use B, I require an instance of A to be provided at compile time". This can be done through mixin

Once you understand that, you can do:

def method(bTrait: B with A) = bTrait.a
Comments