1

i'm trying to understand the behavior of the compiler in this situation

object ImplicitTest extends App {

  def foo[T](implicit x: (String => T)): T = ???

  implicit val bar = (x: String) => x.toInt

  foo
}

the code above does not compile and gives the following error:

ambiguous implicit values: both method $conforms in object Predef of type [A]⇒ <:<[A,A] and value bar in object ImplicitTest of type ⇒ String ⇒ Int match expected type String ⇒ T

as the error says my implicit value is conflicting with another implicit defined in Predef... based on this it seems there is no way to declare an implicit parameter to a function converting a value from a known type to an unknown (generic) type.

Is this due to some technical limitation on the compiler or is just the way it is supposed to work, and i'm violating some constraints i'm not aware of?

4

1 回答 1

2

您在foo调用它时没有提供类型参数(并且由于以下原因,没有其他方法可以推断它),因此编译器很难找到正确的参数和正确的隐式参数。

bar: String => Int在范围内具有隐含,但在创建实例中具有隐含,它们都扩展和创建隐含s。编译器正在为 寻找一些隐式函数,但不确定是哪一个,并且您在范围内有多个。不会优先,因为您没有指定它正在寻找的具体内容。Predef=:=<:<A => BString => AString => TfoobarString => T

这将起作用:

def foo[T](implicit x: (String => T)): T = ???

implicit val bar = (x: String) => x.toInt

foo[Int]
于 2015-09-03T02:52:37.887 回答