Is there an Immediately Invoked Anonymous Function

2019-02-25 18:51发布

问题:

This question already has an answer here:

  • Self Executing Anonymous Functions via Lambdas 2 answers

For example, I might want to do an assignment like this (in JavaScript):

var x = (function () {
    // do some searching/calculating
    return 12345;
})();

And in Java, how can I do something similar with Lambdas? The compiler does not like something like this:

Item similarItem = () -> {
    for (Item i : POSSIBLE_ITEMS) {
        if (i.name.equals(this.name)) return i;
    }
    return null;
}();

回答1:

No because lambdas need a target type. The best you can do is cast the expression:

Item similarItem = ((Supplier<Item>) (() -> {
    for (Item i : POSSIBLE_ITEMS) {
        if (i.name.equals(this.name)) return i;
    }
    return null;
})).get();

You must use the correct Functional Interface for your particular lambda. As you can see, it is very clunky and not useful.


UPDATE

The above code is a direct translation of the JavaScript code. However, converting code directly will not always give the best result.

In Java you'd actually use streams to do what that code is doing:

Item similarItem = POSSIBLE_ITEMS.stream()
                                 .filter(i -> i.name.equals(this.name))
                                 .findFirst()
                                 .orElse(null);

The above code assumes that POSSIBLE_ITEMS is a Collection, likely a List. If it is an array, use this instead:

Item similarItem = Arrays.stream(POSSIBLE_ITEMS)
                         .filter(i -> i.name.equals(this.name))
                         .findFirst()
                         .orElse(null);


标签: java lambda