本文介绍了强制Java Lambda表达式捕获Java中的非最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以让lambda表达式捕获不是有效的final变量?
Is it possible to have a lambda expression capture a variable that is not effectively final?
我知道我的代码可以捕获它们,因此可以很好地工作,目前,我必须创建一个新变量,该变量将要传递给lambda表达式的非最终变量复制.
I know that my code would work perfectly if it could capture them, currently I have to create a new variable that copies the non-final variable I want to pass into a lambda expression.
final SomeClass otherObj;
for(int i = 0; i < 10; i++) {
int a = i;
someObject.method(() -> otherObj.process(a, a+1))
}
我想传递"i",而不用创建一个新的临时变量.
I'd like to pass in 'i' instead of having to create a new temporary variable.
推荐答案
您可以使用java8进行尝试,
You can try this with java8,
IntStream.range(0, 10).forEach(i ->{
someObject.method(() -> otherObj.process(i, i+1))
});
这篇关于强制Java Lambda表达式捕获Java中的非最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!