Java lambdas具有与匿名内部类不同的变量要求
我有一个匿名的内部类和一个等效的lambda。为什么 lambda 的变量初始化规则更严格,是否有比匿名内部类或在构造函数中初始化它更干净的解决方案?
import java.util.concurrent.Callable;
public class Immutable {
private final int val;
public Immutable(int val) { this.val = val; }
// Works fine
private final Callable<String> anonInnerGetValString = new Callable<String>() {
@Override
public String call() throws Exception {
return String.valueOf(val);
}
};
// Doesn't compile; "Variable 'val' might not have been initialized"
private final Callable<String> lambdaGetValString = () -> String.valueOf(val);
}
编辑:我确实遇到了一个解决方法:使用getter for .val