Reputation: 91
I met this situation that when there are overload functions with same number of parameters,the scala compiler couldn't infer the type of my function parameter:
class TypeInfer(self: Int, other: Int) {
def test (num: Int, word: String, fun1: (Int, Int) => Int): Unit = {
fun1(self, other)
}
def test (word: String, num: Int, fun1: (Int, Int) => Int): Unit = {
fun1(self,other)
}
}
object main {
def main(args: Array[String]): Unit = {
val num1:Int = 1
val num2:Int = 1
val num3:Int = 1
val infer = new TypeInfer(num1:Int,num2:Int)
infer.test (num3, "hi", (x, y) => x+y) //error:compiler couldn't infer type of (x,y)=>x+y
}
}
Note that infer.test(num3, "hi", (x:Int, y:Int) => x+y)
does work.
So, it seems that I have to explicitly specify the type of my function parameters. But there is no ambiguity, why couldn't scala compiler infer the type?
Upvotes: 1
Views: 105
Reputation: 170733
There is an inherent tension there: for Scala type inference the notion of expected type is important. For method arguments, this expected type is provided by the method signature; but if there are multiple overloads with same number of parameters, it isn't clear what the expected type should be.
Because of this, the definition of overloading resolution in Scala Specification is quite complicated.
This specific case is actually fixed since Scala 2.12; before that all arguments were initially typed with an undefined expected types, and since then
a function literal with a missing parameter type, is typed with an expected function type that propagates the least upper bound of the fully defined types of the corresponding parameters of the (SAM-converted) function types specified by the ith argument type found in each alternative. All other arguments are typed with an undefined expected type.
Upvotes: 2