Reputation: 795
I found a strange compiling error:
class A
class B
object M {
implicit val mA: M[A] = d => new A
implicit val mB: M[B] = d => new B
}
trait M[K] {
def get(d: D): K
}
object D {
implicit def f[K](d: D)(implicit m: M[K]): K = m.get(d)
}
class D
object Main {
val d = new D
val a: A = d // This line can't compile!
}
That can't compile caused by mA
and mB
conflict.
But that is strange since type B
doesn't match our result type.
If I comment the mB
like this
class A
class B
object M {
implicit val mA: M[A] = d => new A
//implicit val mB: M[B] = d => new B
}
trait M[K] {
def get(d: D): K
}
object D {
implicit def f[K](d: D)(implicit m: M[K]): K = m.get(d)
}
class D
object Main {
val d = new D
val a: A = d // can compile
}
That can compile. Why can't the first case compile?
Upvotes: 0
Views: 96
Reputation: 20436
This happens because when compiler try to find implicit variable to pass as m
to f
it doesn't know expected return type (because it depends on which implicit variable will be selected). It creates kind of circular dependency.
PS: You don't need to make f
implicit to illustrate this problem.
Upvotes: 3