2

Why does partial function application in Scala require a type to be supplied, like in:

def func(a: Int, b: Int) = ???

def func1 = func(_ : Int, 1) // compiles fine

def func1x = func(_, 1) // does not compile
// error: missing parameter type for expanded function ((x$2) => func(x$2, 1))

Why is type not inferred in this case? Would inferring type lead to a complicated or ambiguous grammar, or is the type perhaps not as clear as it seems to me?

Suma
  • 33,181
  • 16
  • 123
  • 191
  • FYI, you can easily avoid situations like that by just giving type annotations to your top level definitions. That's good for documentation purposes anyway. – Cubic Feb 10 '16 at 20:08
  • @Cubic I am afraid I do not understand. Can you show an example how would that look like in this case? – Suma Feb 11 '16 at 07:18

1 Answers1

5

From the compile error you can see that func(_, 1) expands to x => func(x, 1). If you first wrote def f = x => func(x, 1), there is no guarantee that x is an Int. SLS 6.23.1 unfortunately says nothing about filling in the type ascription when one is not explicitly given.

List(1, 2, 3).map(_ + 1) works because map expects an argument of Int => Int. def func1x = func(_, 1) does not work because the type of func1x is inferred from the right-hand-side, but there isn't technically known either. It would only make sense to infer x: Int => f(x, 1), but I'd guess that would add another unnecessary complexity for the compiler to have to handle the corner case for placeholder syntax on method arguments.

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138