What are the rules for a local variable in lambda expression in Java?


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.

  • A lambda expression can't define any new scope as an anonymous inner class does, so we can't declare a local variable with the same which is already declared in the enclosing scope of a lambda expression.
  • Inside lambda expression, we can't assign any value to some local variable declared outside the lambda expression. Because the local variables declared outside the lambda expression can be final or effectively final.
  • The rule of final or effectively final is also applicable for method parameters and exception parameters.
  • The this and super references inside a lambda expression body are the same as their enclosing scope. Because lambda expressions can't define any new scope.

Example

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);
   }
}

Output

x = 10
y = 10
this.x = 2
LambdaTest.this.x = 1

Updated on: 11-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements