【发布时间】:2018-03-14 08:46:30
【问题描述】:
我想在 lambda 函数中使用局部变量,但出现错误: 请看代码中的1.和2.点。
class Foo {
int d = 0; // 1. It compiles, but ugly, 2. doesnt compile
public void findMax(List<List<Route>> routeLists) {
int d = 0; // 2.Error : Local variable dd defined in an enclosing scope must be final or effectively final
routeLists.forEach(e-> {
e.forEach(ee -> {
d+=ee.getDistance();
});
});
... doing some other operation with d
}
}
如何在不将它们设置为全局变量的情况下使用它们?
【问题讨论】:
-
不允许多次声明,d必须是final的,不能在forEach内部修改
-
最近回答:stackoverflow.com/a/49249463/6099347 相同的基本原理甚至适用于 lambdas
标签: java lambda java-8 java-stream local-variables