Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Scala require partial application of curried functions when assigning to a val?

Tags:

scala

currying

In Scala, why is it that a curried function can easily be passed directly to other functions, but when assigning it to a val one needs to also partially apply it with _? For example, given the two functions:

def curried(a: Int)(b: Int) = a + b
def test(a: Int, f: Int => Int) = f(a)

I can easily pass curried to test with:

test(5, curried(5))

and everything is happy. However if I simply call curried(5) I get an error:

scala> curried(5)
<console>:9: error: missing arguments for method curried;
follow this method with `_' if you want to treat it as a partially applied function
              curried(5)

If I change the call to include type information however, it works:

val 'curried: Int => Int = curried(5)

Can anyone explain the rational behind the inconsistency, surely the Scala compiler can infer that the function is Int => Int given the type definition on the original method?

like image 580
Mark Derricutt Avatar asked Mar 08 '13 22:03

Mark Derricutt


1 Answers

The problem is not inferring the type, the problem is inferring your intent. Did you make a mistake, or did you intentionally curry the function?

Alas, the trailing underscore syntax is the formal syntax, and omitting it is syntactical sugar.

like image 94
Daniel C. Sobral Avatar answered Sep 19 '22 05:09

Daniel C. Sobral