Search code examples
javafunctional-programminghigher-order-functionsfunctional-interface

Returning a function from inside another function in Java


Since we can adopt some functional programming concept in Java programming language is it also possible to write a function which returns an other function? Since Higher order functions do that. Just like JavaScript ?

Here is a JavaScript code that returns a function.

function magic() {
  return function calc(x) { return x * 42; };
}

var answer = magic();
answer(1337); // 56154

Solution

  • The closest Java equivalent is this:

    public static void main(String[] args) {
        UnaryOperator<Integer> answer = magic();
        System.out.println(magic().apply(1337));  // 56154
        System.out.println(answer.apply(1337));   // 56154
    }
    
    static UnaryOperator<Integer> magic() {
        return x -> x * 42;
    }