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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 22-Jan-2020 18:18:48
Advertisements