Lambda 表达式的封闭范围定义的变量可以在 lambda 表达式中访问。Lambda 表达式可以访问实例、静态变量和由封闭类定义的方法。它还可以访问“ this”变量(隐式和显式) ,该变量可以是封闭类的实例。Lambda 表达式还设置实例或静态变量的值。
示例interface SimpleInterface {
int func();
}
public class SimpleLambdaTest {
static int x = 50;
public static void main(String[] args) {
SimpleInterface test = () -> x; //使用Lambda访问静态变量
System.out.println("访问静态变量 'x': " + test.func());
test = () -> { //使用Lambda将值设置为变量
return x = 80;
};
System.out.println("设定值 'x': " + test.func());
}
}
输出结果访问静态变量 'x': 50
'x'设定值: 80