Java Lambda Expression Scope








A lambda expression does not define a scope of its own.

If we use keywords this and super in lambda expression inside a method, they act the same as we use them in that method.

Example

The following code outputs the this from a lambda expression. this in the lambda expression refers to the outside class not the lambda expression itself.

import java.util.function.Function;
/*from w  ww .  j a  v  a2  s.  c  o  m*/
public class Main {
  public Main(){
    Function<String,String> func1 = x -> {System.out.println(this);return x ;};
    System.out.println(func1.apply(""));
  }
  public String toString(){
    return "Main";
  }
  public static void main(String[] argv) {
    new Main();
  }
}

The code above generates the following result.





Example 2

The first line in the Main method has a variable definition for x.

If we remove the comment we would get compile time error since it is conflicting with the variable definition of the lambda expression.

This is another demo showing that the lambda expression has the same scope with its outside method. And the lambda expression doesn't create its own scope.

import java.util.function.Function;
// w  w  w  .j a  v a 2  s .c om
public class Main {
  public Main(){
    //int x= 0;
    Function<String,String> func1 = x -> {System.out.println(this);return x ;};
    System.out.println(func1.apply(""));
  }
  public String toString(){
    return "Main";
  }
  public static void main(String[] argv) {
    new Main();
  }
}

The code above generates the following result.