Search code examples
lambdajava-8interfacefunctional-interface

In Function Interface declaration, how to pass another Function Interface as argument?


I want to do something like this -

final Function<Function<Integer, Integer>, Integer> function = (//appropriate syntax)

Is it possible to do so? If yes, what will be the correct syntax?


Solution

  • Of course, it's totally possible, here is an example of how to implement it

    int input = 2;
    Function<Integer, Integer> times10Function = i -> i * 10;
    Function<Function<Integer, Integer>, Integer> minus10Function = func -> func.apply(input) - 10;
    
    Integer result = minus10Function.apply(times10Function);
    System.out.println(result); // 10
    

    The fact you can't do (i -> i + 10) -> ... is the same reason you can't use constants in methods signatures, these are placeholders, not actual implementations and they're thus piloted by the invoker