6

此示例的设置(Scala 2.10.3):

trait S[A]
trait T[A]
implicit class X[A : S](a: A) { def foo() { } }
implicit class Y[A : T](a: A) { def foo() { } }
implicit object I extends S[String]

这编译:

new X("").foo()

这不会:

new Y("").foo()

因为没有隐含T[String]的。

could not find implicit value for evidence parameter of type T[String]
              new Y("").foo()
              ^

因此,我假设 scalac 可以明确地应用从Stringto的隐式转换X

"".foo()

但相反,我们得到:

type mismatch;
 found   : String("")
 required: ?{def foo: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method X of type [A](a: A)(implicit evidence$1: S[A])X[A]
 and method Y of type [A](a: A)(implicit evidence$1: T[A])Y[A]
 are possible conversion functions from String("") to ?{def foo: ?}
              "".foo()
              ^

这是故意的吗?scalac 在枚举候选人时是否不应该考虑每次转换是否真的有效?

4

1 回答 1

4

我的非学术观点是,隐式设计并不是每次看起来都应该起作用的时候起作用。我认为这是一个好主意,否则你很容易陷入隐含的地狱。您可以通过添加更多隐式转换层来扩展您的示例。仅通过查看代码很难判断实际调用了哪个函数。有明确定义的规则,但我只记得如果从代码中看不出发生了什么,它就不起作用。

我会说您的代码违反了One-at-a-time Rule导致违反Non-Ambiguity RuleA : S只是一个语法糖,可以重写为:

implicit class X[A](a: A)(implicit e: S[A]) { def foo() { } }
implicit class Y[A](a: A)(implicit e: T[A]) { def foo() { } }

如果没有解析“第二个”隐式级别(方法参数e),这两个类在编译XY看来都是一样的,因此是模棱两可的。正如链接文档所说:“为了理智,当编译器已经在尝试另一个隐式转换时,它不会插入进一步的隐式转换。

于 2014-02-15T09:23:15.727 回答