Java Reference
In-Depth Information
static Function<Integer, Integer> multiplyCurry(int x) {
return (Integer y) -> x * y;
}
The function returned by multiplyCurry captures the value of x and multiplies it by its argument
y, returning an Integer. This means you can use multiplyCurry as follows in a map to multiply
each element by 2:
Stream.of(1, 3, 5, 7)
.map(multiplyCurry(2))
.forEach(System.out::println);
This will produce the result 2, 6, 10, 14. This works because map expects a Function as argument
and multiplyCurry returns a Function!
Now it's a bit tedious in Java to manually split up a function to create a curried form (especially
if the function has multiple arguments). Scala has a special syntax to do this automatically. You
can define the normal multiply method as follows:
def multiply(x : Int, y: Int) = x * y
val r = multiply(2, 10);
And here is its curried form:
Using the (x: Int)(y: Int) syntax, the multiplyCurry method takes two argument lists of one Int
parameter. In contrast, multiply takes one list of two Int parameters. What happens when you
call multiplyCurry? The first invocation of multiplyCurry with a single Int (the parameter x),
multiplyCurry(2), returns another function that takes a parameter y and multiplies it with the
captured value of x (here the value 2). We say this function is partially applied as explained in
section 14.1.2 , because not all arguments are provided. The second invocation multiplies x and y.
This means you can store the first invocation to multiplyCurry inside a variable and reuse it:
 
Search WWH ::




Custom Search