Question

What is the difference between def f(x: Int)(y: Int) = x + y and def f(x: Int) = (y: Int) => x + y?

The REPL doesn’t seem happy when I treat the former the same as the latter:

scala> def f(x: Int)(y: Int) = x + y
f: (x: Int)(y: Int)Int

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

scala> def f(x: Int) = (y: Int) => x + y
f: (x: Int)Int => Int

scala> f(42)
res2: Int => Int = <function1>

What are the exact differences and when should I use which form?

Was it helpful?

Solution

The difference is

def f(x: Int)(y: Int) = x + y

is a curried function. A function with two parameterlists. You can use it with just one argument, but you need to specify which one.

f(42) _ // this is short for f(42)(_: Int)

will generate a partial applied function, where the value of x is 42. You could also do:

f(_: Int)(42) // note: the first parameter must be used this way

This will set the value of y to 42.
Calling a curried function with just a few parameters will generate a partial applied function.

def f(x: Int) = (y: Int) => x + y

is a partial applied function. Here you have a function which takes one argument and returns a function which takes an argument itself.

OTHER TIPS

With first syntax, you need to add _ as suggested by the compiler

scala> f(42) _
res1: Int => Int = <function1>

cf : Why and when do I need to follow a method name with _?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top