Kidus Tekeste
Kidus Tekeste

Reputation: 661

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

Upvotes: 1

Views: 3984

Answers (3)

WJS
WJS

Reputation: 40034

Here's another example I wrote a while back. It returns a conversion function base on supplied arguments.

// generate a Celsius to Fahrenheit Converter.
DoubleUnaryOperator cToF = conversionGen(9 / 5., 32);

// Fahrenheit to Celsius
DoubleUnaryOperator fToC =
        conversionGen(5 / 9., (-32 * 5 / 9.));

// kilometers to miles
DoubleUnaryOperator kiloToMiles = conversionGen(.6, 0);

// and pounds to Kilograms.
DoubleUnaryOperator lbsToKgms = conversionGen(1 / 2.2, 0);

Now all you have to do is call them with the single argument.

double farTemp = cToF.applyAsDouble(100);
double celTemp = fToC.applyAsDouble(212);
System.out.println(farTemp);
System.out.println(celTemp);
System.out.println(kiloToMiles.applyAsDouble(1500));
System.out.println(lbsToKgms.applyAsDouble(4.4));

Prints

212.0
100.0
900.0
2.0     

The generator.

public static DoubleUnaryOperator conversionGen(double factor,
            double base) {
        return unit -> unit * factor + base;
}

Upvotes: 1

Nikolas
Nikolas

Reputation: 44398

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;
}

Upvotes: 4

michid
michid

Reputation: 10814

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);
}

Upvotes: 1

Related Questions