Currying is the technique of transforming a function with multiple arguments into a function with just one argument. The single argument is the value of the first argument from the original function and the function returns another single argument function. This in turn would take the second original argument and itself return another single argument function. This chaining continues over the number of arguments of the original. The last in the chain will have access to all of the arguments and so can do whatever it needs to do.
You can turn any function with multiple arguments into it’s curried equivalent. Let’s have a look at this in action.
For example, in Java, you can convert
into something like this (where
Function<A, B> defines a single method
B apply(A a)).
Calling the original method
and calling the curried version
In Java 8, it’s much less verbose using the new lambda syntax.
In Scala, the regular uncurried function would look like this.
As Scala supports curried functions, you can turn this into it’s curried version simply by separating out the arguments.
Which is shorthand for writing it out like this.
Using the REPL to show how they’re called;
and working with the longhand version;
It turns out that it’s this partial application of functions that’s really interesting. Currying in Scala allows us to defer execution and reuse functions. We’ll have a look at that in the next article.