是否可以在 lambda 主体或匿名 class 中使用无效的最终或最终变量?
Is it possible to use not effectively final or final variable in lambda body or anonymous class?
是否可以在 lamba body 中使用既不是有效 final 也不是 final 的变量?
那么有没有办法让下面的代码编译通过呢?
class Main {
interface Test{
String method();
}
void w(){
String str = "foo";
str = "bar";
Test t = () -> str;
}
}
是的,有可能。
您可以将您的值复制到 effectively final local variable:
class Main {
interface Test{
String method();
}
void w(){
String str = "foo";
str = "bar";
String tmpStr = str;
Test t = () -> tmpStr;
}
}
从现在起你的临时值是有效的最终值,你可以在 lambda 表达式或匿名中使用它 类。
是否可以在 lamba body 中使用既不是有效 final 也不是 final 的变量?
那么有没有办法让下面的代码编译通过呢?
class Main {
interface Test{
String method();
}
void w(){
String str = "foo";
str = "bar";
Test t = () -> str;
}
}
是的,有可能。
您可以将您的值复制到 effectively final local variable:
class Main {
interface Test{
String method();
}
void w(){
String str = "foo";
str = "bar";
String tmpStr = str;
Test t = () -> tmpStr;
}
}
从现在起你的临时值是有效的最终值,你可以在 lambda 表达式或匿名中使用它 类。