Question

Let's define f, a function that supports currying :

def f(a: Int)(b: Int) = a + b

This code doesn't compile

def g= f(1)
<console>:10: error: missing arguments for method f;
follow this method with `_' if you want to treat it as a partially applied function
   def g= f(1)

I've found these 2 workarounds :

scala> def h = f(1) _
h: Int => Int

scala> def i : Int => Int = f(1)
i: Int => Int

But i don't understand why the inference engine need help in a trivial case like that ?

Was it helpful?

Solution

This is because def f(a: Int)(b: Int) is not a function but a method with multiple parameter lists. Scala doesn't unify both of them to a single concept, thus you have to distinguish between them as well.

To partially apply a method with multiple parameter lists (and therefore implicitly convert this method to a function) you have to add an underscore after the method, as the error message suggests. When you tell the compiler explicitly which signature you want to have, it can also implicitly convert a method to a function (as seen in your second workaround).

If you want to use currying in Scala it's best to create a function from the beginning:

scala> val f = (a: Int) => (b: Int) => a+b
f: Int => (Int => Int) = <function1>

scala> val g = f(1)
g: Int => Int = <function1>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top