A lambda expression can capture variables like local and anonymous classes. In other words, they have the same access to local variables of the enclosing scope. We need to follow some rules in case of local variables in lambda expressions.
import java.util.function.Consumer; public class LambdaTest { public int x = 1; class FirstLevel { public int x = 2; void methodInFirstLevel(int x) { Consumer<Integer> myConsumer = (y) -> { // Lambda Expression System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("this.x = " + this.x); System.out.println("LambdaTest.this.x = " + LambdaTest.this.x); }; myConsumer.accept(x); } } public static void main(String args[]) { final LambdaTest outerClass = new LambdaTest(); final LambdaTest.FirstLevel firstLevelClass = outerClass.new FirstLevel(); firstLevelClass.methodInFirstLevel(10); } }
x = 10 y = 10 this.x = 2 LambdaTest.this.x = 1