scalatype-inferencepartially-applied-type

Why scala does not infer type in partially applied function?


Given scala's type inference, I'd expect following not to fail:

scala> def partiallyApplied(x: Int, y: Int, z: Int) = x + y + z
partiallyApplied: (x: Int, y: Int, z: Int)Int

scala> val partialSum = partiallyApplied(2, 3, _)
<console>:11: error: missing parameter type for expanded function ((x$1) => partiallyApplied(2, 3, x$1))
   val partialSum = partiallyApplied(2, 3, _)
                                           ^

And of course, this works:

scala> val partialSum = partiallyApplied(2, 3, _:Int)
partialSum: Int => Int = <function1>

Is there a reason why type inference does not help with partially applied function in this case?


Solution

  • Scala specification says exactly in which cases parameter types can be omitted and this isn't one of them:

    If the expected type of the anonymous function is of the shape scala.FunctionN[S1,…,Sn, R], or can be SAM-converted to such a function type, the type Ti of a parameter xi can be omitted, as far as Si is defined in the expected type, and Ti = Si is assumed. Furthermore, the expected type when type checking e is R.

    If there is no expected type for the function literal, all formal parameter types Ti must be specified explicitly, and the expected type of e is undefined. The type of the anonymous function is scala.FunctionN[T1,…,Tn, R], where R is the packed type of e. R must be equivalent to a type which does not refer to any of the formal parameters xi.

    Could it be changed to work in this specific case as well? Sure. Is the change worth it? Probably not.