Functional Programming with Java - Currying



Currying is a technique where a many arguments function call is replaced with multiple method calls with lesser arguments.

See the below equation.

(1 + 2 + 3) = 1 + (2 + 3) = 1 + 5 = 6

In terms of functions:

f(1,2,3) = g(1) + h(2 + 3) = 1 + 5 = 6

This cascading of functions is called currying and calls to cascaded functions must gives the same result as by calling the main function.

Following example shows how Currying works.

import java.util.function.Function;

public class FunctionTester {
   public static void main(String[] args) {
      Function<Integer, Function<Integer, Function<Integer, Integer>>> 
         addNumbers = u -> v -> w -> u + v + w;             
      int result = addNumbers.apply(2).apply(3).apply(4);        
      System.out.println(result);
   } 
}

Output

9
Advertisements