In Java would a variable receive a function like in Javascript?

Asked

Viewed 78 times

6

Example:

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

Could it be? Or is it a feature of Javascript?

2 answers

3


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

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

I put in the Github for future reference.

Of course it differs in the question 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 larger context I don’t know if this is the best way to case. See more options.

I can’t tell you if in Java 15 or 16 you can use var in place of the type (I think not, need to search).

  • For functions with 2 arguments only.

  • Cool! This in java could be efficient in which Maniero context ?

  • Just one example, please.

  • 1

    This is the form for 2 arguments. Has for one and should have for more, but in Java I do not know the exact mechanisms, I would need to search. It is not efficiency, on the contrary, this is less efficient because it has indirect extra. This is used to parameterize actions into codes that you know almost everything to do, but there is a point that the consumer must define what to perform. It’s the same as JS.

  • Thank you very much Maniero!!!

-1

No... the nearest would be:

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

or

metodoTeste(() -> System.out.println("Hello"));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.