In Java would I have as a variable to receive a function as in JavaScript?

6

Example:

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

Would you like it? Or is it a JavaScript feature?

    
asked by anonymous 21.08.2018 / 17:46

2 answers

3

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;

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

You have other ways to declare according to need and number of arguments. Without a larger context I do not know if this is the best form for the case. See more options .

I can not tell you whether Java 10 can use var instead of type (I think not). I'll search.

    
21.08.2018 / 17:51
-1

No ... the closest would be:

metodoTeste(new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello");
    }
});

or

metodoTeste(() -> System.out.println("Hello"));
    
21.08.2018 / 17:50