What are the scoping rules for lambda expressions in Java?


There are different scoping rules for lambda expression in Java. In lambda expressions, this and super keywords are lexically scoped means that this keyword refers to the object of the enclosing type and the super keyword refers to the enclosing superclass. In the case of an anonymous class, they are relative to the anonymous class itself. Similarly, local variables declared in lambda expression conflicts with variables declared in the enclosing class. In the case of an anonymous class, they are allowed to shadow variables in the enclosing class.

Example

@FunctionalInterface
interface TestInterface {
   int calculate(int x, int y);
}
class Test {
   public void showValue(String str) {
      System.out.println("The value is: " + str);
   }
}
public class LambdaExpressionTest extends Test {
   public static void main(String[] args) {
      LambdaExpressionTest lambdaObj = new LambdaExpressionTest();
      lambdaObj.getResult();
   }
   public void getResult() {
      TestInterface ref = (x, y) -> {     // lambda expression
         System.out.println("The toString: " + this.toString());
         super.showValue("Calling from Lambda");
         return x*y;
      };
      System.out.println("Result is: " + ref.calculate(8, 6));
   }
}

Output

The toString: LambdaExpressionTest6@87aac27
The value is: Calling from Lambda
Result is: 48

Updated on: 10-Jul-2020

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements