在 JavaScript 中,可以按照以下方式做一些事情:var qwerty = (function() { //some code return returnValue;}这会将returnValue分配给qwerty。有没有办法在 Java 中做类似的事情?就像是:int num = { public int method() { //some code return val; }}我知道我可以写出一个单独的方法,但我想以类似于上面的方式来做,因为它在我正在编写的代码中看起来更整洁。
1 回答

慕标琳琳
TA贡献1830条经验 获得超9个赞
因为您function没有指定任何参数,所以您很可能正在寻找IntSupplier功能接口:
IntSupplier supplier = () -> {
int val = ...;
//some code
return val;
};
int num = supplier.getAsInt();
如果你真的想内联它,那么你可以使用以下内容(这是不可读的,所以我不推荐它):
int num = ((IntSupplier) () -> {
int val = ...;
//some code
return val;
}).getAsInt();
因为上面IntSupplier没有存储在变量中,所以它在逻辑上等同于以下内容:
int val = ...;
//some code
int num = val;
添加回答
举报
0/150
提交
取消