隐式参数和泛型

implicit parameters and generic types

我正在尝试了解编译器在这种情况下的行为

object ImplicitTest extends App {

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

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

  foo
}

上面的代码无法编译并给出以下错误:

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

正如错误所说,我的隐式值与 Predef 中定义的另一个隐式值冲突...基于此,似乎无法为将值从已知类型转换为未知类型的函数声明隐式参数(通用)类型。

这是由于编译器的某些技术限制还是它应该工作的方式,我违反了一些我不知道的限制?

调用它时没有向 foo 提供类型参数(并且没有其他方法可以推断它,原因如下),因此编译器无法找到正确的参数, 右隐式。

你在范围内有隐式 bar: String => Int,但你 也有 Predef 中有隐式,它创建 =:=<:< 既扩展了 A => B,又创建了隐含的 String => A。编译器正在寻找 some implicit function String => T for foo,但不确定是哪一个,而且你有多个范围。 bar 不会优先,因为您没有指定它要查找的具体 String => T

这会起作用:

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

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

foo[Int]