这是我之前发布的模糊隐式转换错误的一个更简单的版本
这是帖子中的代码片段如何在 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
和隐式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)
}
我不明白say 的转换函数bToC
和可能的转换函数如何。dToC
println(new B(5, 5).total)