是否可以将方法的返回值直接分配给变量?

Min*_*ing 5 java methods

在JavaScript中,可以按照以下步骤进行操作:

var qwerty = (function() {
    //some code
    return returnValue;
}
Run Code Online (Sandbox Code Playgroud)

这将分配的returnValue到QWERTY键盘。有没有办法用Java做类似的事情?就像是:

int num = {
    public int method() {
        //some code
        return val;
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以写出一个单独的方法,但是我想以与上面类似的方式来做,因为它在我编写的代码中看起来更加整洁。

Jac*_* G. 4

因为您function没有指定任何参数,所以您很可能正在寻找IntSupplier功能接口:

IntSupplier supplier = () -> {
    int val = ...;
    //some code
    return val;
};

int num = supplier.getAsInt();
Run Code Online (Sandbox Code Playgroud)

如果你真的想内联它,那么你可以使用以下内容(这是不可读的,所以我不推荐它):

int num = ((IntSupplier) () -> {
    int val = ...;
    //some code
    return val;
}).getAsInt();
Run Code Online (Sandbox Code Playgroud)

因为上面的内容IntSupplier没有存储在变量中,所以它在逻辑上等价于以下内容:

int val = ...;
//some code
int num = val;
Run Code Online (Sandbox Code Playgroud)