How to access variables from enclosing class using lambda in Java?


The variables defined by the enclosing scope of a lambda expression can be accessible within the lambda expression. A lambda expression can access to both instance, static variables and methods defined by the enclosing class. It has also access to "this" variable (both implicitly and explicitly) that can be an instance of enclosing class. The lambda expression also sets the value of an instance or static variable.

Example

interface SimpleInterface {
   int func();
}
public class SimpleLambdaTest {
   static int x = 50;
   public static void main(String[] args) {
      SimpleInterface test = () -> x;     // Accessing of static variable using lambda
      System.out.println("Accessing static variable 'x': " + test.func());

      test = () -> {     // Setting the value to variable using lambda
         return x = 80;
      };
      System.out.println("Setting value for 'x': " + test.func());
   }
}

Output

Accessing static variable 'x': 50
Setting value for 'x': 80

Updated on: 14-Jul-2020

588 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements