This is a much simpler version of my earlier post ambiguous implicit conversion errors
Here is a code snippet from the post How can I chain implicits in Scala?
class A(val n: Int)
class B(val m: Int, val n: Int)
class C(val m: Int, val n: Int, val o: Int) {
def total = m + n + o
}
object T2 {
implicit def toA(n: Int): A = new A(n)
implicit def aToB[A1 <% A](a: A1): B = new B(a.n, a.n)
implicit def bToC[B1 <% B](b: B1): C = new C(b.m, b.n, b.m + b.n)
// works
println(5.total)
println(new A(5).total)
println(new B(5, 5).total)
println(new C(5, 5, 10).total)
}
Now if I add a class D
and implicit def dToC
as follows, I get errors at locations shown in the snippet.
class A(val n: Int)
class B(val m: Int, val n: Int)
class D(val m: Int, val n: Int) //Added by me
class C(val m: Int, val n: Int, val o: Int) {
def total = m + n + o
}
object T2 {
implicit def toA(n: Int): A = new A(n)
implicit def aToB[A1 <% A](a: A1): B = new B(a.n, a.n)
implicit def bToC[B1 <% B](b: B1): C = new C(b.m, b.n, b.m + b.n)
implicit def dToC[D1 <% D](d: D1): C = new C(d.m, d.n, d.m + d.n) //Added by me
println(5.total) //Ambiguous implicit conversion error
println(new A(5).total) //Ambiguous implicit conversion error
println(new B(5, 5).total) //Ambiguous implicit conversion error
println(new C(5, 5, 10).total)
}
I don't understand how both bToC
and dToC
are possible conversion functions for say println(new B(5, 5).total)
.
class A
,def toA
anddef aToB
, the ambiguity remains (but I also don't see, why). – Malte Schwerhoffclass A
makes sense as an independent post. But I keptclass A
so that people can correlate with the nice explanation in the How can I chain implicits in Scala? post. – dips