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
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;
}
Yes you can
Function<String, Integer> getLengthFunction() {
return String::length;
}
And you can take this further. E.g. implement currying:
static <T, U, R> Function<T, Function<U, R>> curry(BiFunction<T, U, R> f) {
return t -> u -> f.apply(t, u);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With