Java - Lambda Expressions Lexical Scoping

Introduction

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

It exists in its enclosing scope.

For example, when a lambda expression is used inside a method, the lambda expression exists in the scope of the method.

The keywords this and super are the same inside the lambda expression and its enclosing method.

Example

The program creates two instances of the Printer interface.

Both instances use the keyword this inside the print() method.

Both methods print the class name that the keyword this refers to.

The keyword this has the same meaning inside the getLambdaPrinter() method and the lambda expression.

Demo

@FunctionalInterface
interface Printer {
  void print(String msg);
}

public class Main {
  public static void main(String[] args) {
    Main test = new Main();
    Printer lambdaPrinter = test.getLambdaPrinter();
    lambdaPrinter.print("Lambda Expressions");

    Printer anonymousPrinter = test.getAnonymousPrinter();
    anonymousPrinter.print("Anonymous Class");
  }/*from  www. j a va 2  s. com*/

  public Printer getLambdaPrinter() {
    System.out.println("getLambdaPrinter(): " + this.getClass());

    Printer printer = msg -> {
      System.out.println(msg + ": " + this.getClass());
    };

    return printer;
  }

  public Printer getAnonymousPrinter() {
    System.out.println("getAnonymousPrinter(): " + this.getClass());

    Printer printer = new Printer() {
      @Override
      public void print(String msg) {
        System.out.println(msg + ": " + this.getClass());
      }
    };

    return printer;
  }
}

Result

Related Topics

Quiz