5

Sample code with two overload method compiles (Scala 2.11.8), as expected:

def foo(p: Int, t: Double): Unit = {}
def foo(r: Int => Double): Unit = {}

foo(0, 0) // 1st method
foo(x => x.toDouble) // 2nd method

Same code with generic parameter added:

def fooGeneric[T](p: T, t: Double): Unit = {}
def fooGeneric[T](r: T => Double): Unit = {}

fooGeneric[Int](1, 1) // 1st method
fooGeneric[Int]((x: Int) => x.toDouble) //2nd method

fooGeneric[Int](x => x.toDouble) // does not compile

yields the following compilation error:

Error:(112, 19) missing parameter type
fooGeneric[Int](x => x.toDouble)

There seems to be is no ambiguity in the method resolution, yet compiler fails to find the match. Why?

Kamil Kloch
  • 333
  • 1
  • 9
  • 4
    It seems there is an interaction between overload resolution and type inference. This very recent [SI-10074](https://issues.scala-lang.org/browse/SI-10074) reports this very issue. – b-studios Nov 23 '16 at 12:31
  • Sidenote that does not answer your question: the latest version of [Dotty](https://github.com/lampepfl/dotty) compiles your example without any complaints. – b-studios Nov 23 '16 at 12:36
  • See if this helps: http://stackoverflow.com/a/4916606/4496364 – insan-e Nov 23 '16 at 12:41
  • The following compiles - `fooGeneric[Int]{ x: Int => x.toDouble }` – Kevin Meredith Nov 23 '16 at 13:35
  • You could do this but not ideal I guess - `def fooGeneric[T, U <: Double](r: T => U): Unit = {}` then `fooGeneric[Int, Double](x => x.toDouble)` – jacks Nov 23 '16 at 15:13
  • 1
    @Nio Yes, adding a phantom generic type solves the problem. A bit hacky, though :) – Kamil Kloch Nov 24 '16 at 13:55

0 Answers0