我们可以在Java的lambda表达式中访问哪种变量?
lambda表达式由两个部分组成,一个是参数 ,另一种是一个表达 ,并且这两个部件都用箭头分离(->)符号。Lambda表达式可以访问其封闭 范围的变量。
Lambda表达式访问这两个实例 和静态 的变量,它是包类,也可以访问本地 变量 它们是有效的最终或最后。
语法
( argument-list ) -> expression
示例
interface TestInterface {
void print();
}
public class LambdaExpressionTest {
int a; // instance variable static int b; // static variable LambdaExpressionTest(int x) { // constructor to initialise instance variable this.a = x;
}
void show() {
// lambda expression to define print() method TestInterface testInterface = () -> { // accessing of instance and static variable using lambda expression System.out.println("Value of a is: "+ a);
System.out.println("Value of b is: "+ b);
};
testInterface.print();
}
public static void main(String arg[]) {
LambdaExpressionTest test = new LambdaExpressionTest(10);
test.show();
}
}输出结果
Value of a is: 10 Value of b is: 0