隐式转换不适用,因为它们不明确

时间:2014-09-21 17:13:14

标签: scala compiler-errors implicit-conversion scala-2.10

class Foo

implicit def fromInt[A <% Int](x: A) = new Foo       // #1
implicit def fromString[A <% String](x: A) = new Foo // #2

0: Foo

给出

error: type mismatch;
 found   : Int(0)
 required: this.Foo
Note that implicit conversions are not applicable because they are ambiguous:
 both method fromInt of type [A](x: A)(implicit evidence$1: A => Int)this.Foo
 and method fromString of type [A](x: A)(implicit evidence$2: A => String)this.Foo
 are possible conversion functions from Int(0) to this.Foo
0: Foo
^

我不确定我理解。

如果我删除了#2,它就会编译。

如果删除#1,则无法编译

error: No implicit view available from Int => String.
0: Foo
^

没有歧义。 fromString IntFoo的转换函数。

为什么编译器声称存在歧义?

1 个答案:

答案 0 :(得分:1)

这似乎是2.9.x和2.10.x中的错误。

它在2.11.2中修复。

https://issues.scala-lang.org/browse/SI-8857