I'm starting to learn a little Scala, and I basically understand functions that return functions and currying, but I've seen two syntaxes for doing this, and I'd like to better understand the differences, and maybe a little of theory behind what's going on.
In the first method (using =>
) I can curry the function by just specifying
the argument to be bound to variable x
. However when I try to do this
with the second approach, the compiler tells me I need to specify the _
wild card for the second argument.
I understand what I need to do but I am not sure why I need to do things this way. Can someone please tell me what the Scala compiler is doing here?
First Method using =>
def add(x:Int) = (y:Int) => x + (-y)
add: (x: Int)Int => Int
scala> def adder = add(100) // x is bound to 100 in the returned closure
adder: Int => Int
scala> adder(1)
res42: Int = 99
Second Method using one arg list followed by another
scala> def add2(x:Int)(y:Int) : Int = x + y
add2: (x: Int)(y: Int)Int
scala> def adder2 = add2(100)
<console>:9: error: missing arguments for method add2;
follow this method with `_' if you want to treat it
as a partially applied function
def adder2 = add2(100)
^
scala> def adder2 = add2(100) _ // Okay, here is the '_'
adder2: Int => Int
scala> adder2(1) // Now i can call the curried function
res43: Int = 101