Lambda表达式中的变量赋值 [英] Variable assignment in lambda expression
问题描述
我有以下代码片段:
SomeClass someClass;
switch (type) {
case FIRST:
someClass = new SomeClass();
break;
case SECOND:
OptionalLong optional = findSomeOptional();
optional.ifPresent(value -> someClass = new SomeClass(value));
}
并且我试图在lambda表达式中将新对象分配给 someClass 引用,但是随后出现错误消息:在lambda中使用的变量应该有效地是最终的" .
And I'm trying to assign new object to someClass reference in lambda expresion but then I've got error message: "variable used in lambda should be effectively final".
当我在someClass的声明中添加 final 时,出现了另一个错误无法为最终变量赋值"
When I add final to declaration of someClass I got another error "cannot assign value to final variable"
那么我该如何巧妙地处理lamda中的此类征兆?
So how can I smartly deal with such assigment in lamdas?
推荐答案
简单的答案是您不能在lambda表达式中分配上层的局部变量.
您可以将变量变成实例成员,或者使用简单的if语句:
The simple answer is you cannot assign local variables from upper levels in lambda expressions.
Either, you turn your variable into an instance member, or use an simple if statement:
SomeClass someClass;
switch (type) {
case FIRST:
someClass = new SomeClass();
break;
case SECOND:
OptionalLong optional = findSomeOptional();
if(optional.isPresent()) {
someClass = new SomeClass(optional.getAsLong());
}
}
最后一个选择是使用AtomicReference
.
这篇关于Lambda表达式中的变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!