Reputation: 661
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
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
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