Functional Programming - Returning a Function



As a High Order function can return a function but how to implement using Java 8. Java 8 has provided Function interface which can accept a lambda expression. A high order function can return a lamdba expression and thus this high order function can be used to create any number of functions. See the example below −

import java.util.function.Function;

public class FunctionTester {    
   public static void main(String[] args) {               
      Function<Integer, Integer> addOne = adder(1);
      Function<Integer, Integer> addTwo = adder(2);
      Function<Integer, Integer> addThree = adder(3);

      //result = 4 + 1 = 5
      Integer result = addOne.apply(4);
      System.out.println(result);

      //result = 4 + 2 = 6
      result = addTwo.apply(4);
      System.out.println(result);

      //result = 4 + 3 = 7
      result = addThree.apply(4);
      System.out.println(result);
   }

   //adder - High Order Function
   //returns a function as lambda expression
   static Function<Integer, Integer> adder(Integer x){
      return y -> y + x;
   }
}

Output

5
6
7
Advertisements