2

In the following code:

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

In the assignment of x, why can't the compiler infer that the type of fooImplicitGetter is Int, and therefore it needs to use the FooInt instance, as it can in the assignment of y? Is there any way of helping it other than fooImplicitGetter[Int], passing FooInt explicitly, etc.? This is under 2.11 if it matter.

EDIT: This appears to be the same issue mentioned here: Inferring type of generic implicit parameter from return type, so I've modified my example to match. I'm also fine with closing it for duplication, unless someone has an answer.

Gal
  • 5,338
  • 5
  • 33
  • 55
  • Please add an actual implementation of `fooGetter` where the inference engine resolves `T`. – jwvh Jul 04 '17 at 08:23
  • You could pass the implicit explicitly, but then what's the point? Is this what you're actually trying to achieve? I'm having hard time making sense of the example. – Yuval Itzchakov Jul 04 '17 at 08:56
  • @jwvh: Why does the actual implementation matter? It's not as if replacing fooImplicitGetter's implementation with ??? works. The compiler doesn't look at the implementation. – Gal Jul 04 '17 at 10:40
  • @YuvalItzchakov I don't want to pass the implicit explicitly, obviously. I said as much in the text. I want the compiler to infer that the correct type for fooImplicitGetter is Int. – Gal Jul 04 '17 at 10:40

0 Answers0