查看边界和模糊的隐式转换错误

时间:2012-07-30 06:58:39

标签: scala implicit-conversion

这是我早期帖子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) 
}

我不明白bToCdToC如何成为println(new B(5, 5).total)的转换函数。

2 个答案:

答案 0 :(得分:1)

查看边界显然会转换为额外的隐式函数参数。因此,bToCdToC都会转换为[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个路径,并且编译器不知道要去哪个路径,这就是为什么引发了模糊的隐式转换错误。