2020-03-04

Lambda expressions - Lexical scoping

Lexical scoping

Lambda expression uses a very simple approach to handle resolution of names in the body. Lambda expressions don’t introduce a new level of scoping.

They are lexically scoped, which means names in lambda expression’s body are interpreted as they are in the expression’s enclosing context. So lambda expression body is executed as it’s in the same context of code enclosing it, except that the body can also access expression’s formal parameters. this used in the expression body has the same meaning as in the enclosing code.

Lexical scoping of lambda expression

public void run() { 
String name = "Alex"; 
new Thread(() -> System.out.println("Hello, " + name)).start(); 


this in lambda expression
public class LambdaThis {
private String name = "Alex";
public void sayHello() {
System.out.println("Hello, " + name);
}
public void run() {
new Thread(() -> this.sayHello()).start();
}
public static void main(String[] args) {
new LambdaThis().run();
}
}


No comments:

Post a Comment