In Java, would a variable receive a function just like in JavaScript?



var x = function (a, b) {
           return a * b 

Would? Or is it a feature of JavaScript?


In Java 8 you can use lambda syntax. Before that just creating functors , which is not exactly the same thing, but gives similar results.

BiFunction<Integer, Integer, Integer> x = (a, b) -> a * b;

I put it on GitHub for future reference .

Of course it differs in that everything is typed, but it's that simple.

There are other ways to declare according to the need and number of arguments. Without a bigger context I don't know if this is the best way for the case. See more options .

I can't tell you if in Java 15 or 16 you can use var instead of type (I don't think so, you need to search).

Scroll to Top