2

在以下代码中:

trait Foo[T] {
  def get: T
}
implicit object FooInt extends Foo[Int] {
  override def get = 0
}
implicit object FooString extends Foo[String] {
  override def get = "0"
}
def fooImplicitGetter[T](implicit ev: Foo[T]): T = ev.get

val x: Int = fooImplicitGetter // Does not compile; ambiguous implicit values error


implicit val int = 0
implicit val string = ""
def implicitGetter[T](implicit ev: T): T = ev

val y: Int = implicitGetter // Compiles just fine

在 的赋值中x,为什么编译器不能推断 fooImplicitGetter 的类型是Int,因此它需要使用FooInt实例,因为它可以在 的赋值中y?除了明确fooImplicitGetter[Int]传递等之外,还有什么方法可以帮助它吗?FooInt如果重要的话,这低于 2.11。

编辑:这似乎与此处提到的相同问题:Inferring type of generic implicit parameter from return type,所以我修改了我的示例以匹配。我也可以关闭它以进行重复,除非有人有答案。

4

0 回答 0