这是我早期帖子ambiguous implicit conversion errors
的一个更简单的版本以下是帖子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)
}
现在,如果我按如下方式添加课程D
和隐式def dToC
,我会在代码段中显示的位置收到错误。
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)
}
我不明白bToC
和dToC
如何成为println(new B(5, 5).total)
的转换函数。
答案 0 :(得分:1)
查看边界显然会转换为额外的隐式函数参数。因此,bToC
和dToC
都会转换为[T](x: T)(implicit f: T => Something): C
问题是编译器在模糊检查中忽略隐式参数的存在/不存在。
case class Foo[A](value: A)
implicit def foo[A](x: A)(implicit ev: Any =:= String) = Foo(x)
implicit def bar[A](x: A)(implicit ev: Any =:= Int) = Foo(x)
1.value //Ambiguous though none are applicable
答案 1 :(得分:-1)
(1)Int =&gt; A =&gt; B =&gt; C
(2)Int =&gt; A =&gt; D =&gt; C
可以选择2个路径,并且编译器不知道要去哪个路径,这就是为什么引发了模糊的隐式转换错误。