Scala 使用带有隐式参数的泛型方法时隐式值不明确
在以下代码中:Scala 使用带有隐式参数的泛型方法时隐式值不明确,scala,scala-implicits,Scala,Scala Implicits,在以下代码中: 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
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
的赋值中一样?除了显式地传递FooInt
等,还有什么方法可以帮助它呢。?如果有关系,这在2.11以下
编辑:这似乎与这里提到的问题相同:,所以我修改了我的示例以匹配。我也可以关闭它进行复制,除非有人有答案。请添加一个实际的
fooGetter
实现,其中推理引擎解析T
。您可以显式传递隐式,但这有什么意义?这是你真正想要实现的吗?我很难理解这个例子。@jwvh:为什么实际的实现很重要?这不像是用???取代fooImplicitGetter的实现???作品编译器没有查看实现。@显然,YuvalItzchakov我不想显式传递隐式。我在课文中也说过同样的话。我希望编译器推断fooImplicitGetter的正确类型是Int。