Reputation: 1356
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?
Upvotes: 0
Views: 47
Reputation: 1356
The answer posted by Yassin Hajaj is perfect. However, I came up with an even better example for clearer understanding -
final int base1 = 3;
final int base2 = 5;
final int index = 2;
final Function<BiFunction<Integer, Integer, Integer >, Function<Integer, Integer>> power = func ->
myIndex -> {
int result = 1;
int base = func.apply(base1, base2);
for (int i = 1; i <= myIndex; i++) {
result *= base;
}
return result;
};
final BiFunction<Integer, Integer, Integer> addition = (num1, num2) -> num1 + num2;
final int result = power.apply(addition).apply(index);
System.out.println("Result: " + result);
Output -
Result: 64
Here, there are two functions.
addition
function's job is to define addition of two numbers.
power
function takes addition
function as argument, performs the addition of base1
and base2
to get the base
. As a second argument power
takes the index
and then performs the power operation of base to the power index and returns the result.
Upvotes: 0
Reputation: 21975
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
Upvotes: 2