Java是否有立即调用的匿名函数? [英] Is there an Immediately Invoked Anonymous Function for Java?

查看:78
本文介绍了Java是否有立即调用的匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我可能想要这样做(在JavaScript中):

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

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

在Java中,我怎样才能与Lambdas做类似的事情?编译器不像
这样的东西:

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;
}();


推荐答案

否,因为lambdas需要目标类型。您可以做的最好的是转换表达式:

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();

您必须为特定的lambda使用正确的功能接口。正如你所看到的,它非常笨重而且无用。

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

UPDATE

以上代码是JavaScript代码的直接翻译。但是,直接转换代码并不总能得到最好的结果。

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

在Java中你实际上使用 streams 执行该代码正在执行的操作:

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);

上述代码假定 POSSIBLE_ITEMS 是一个收藏,可能是列表。如果是数组,请改为使用:

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是否有立即调用的匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆