Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 231
Kidus Tekeste Avatar asked Apr 29 '26 11:04

Kidus Tekeste


2 Answers

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;
}
like image 199
Nikolas Charalambidis Avatar answered May 04 '26 08:05

Nikolas Charalambidis


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);
}
like image 30
michid Avatar answered May 04 '26 09:05

michid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!