Java - Lambda Expressions Variables Scope

Introduction

A lambda expression variables declared including its parameters exist in the enclosing scope.

Simple names in a scope must be unique.

A lambda expression cannot redefine variables with the same name that already exist in the enclosing scope.

The following code generates a compile-time error as its parameter name msg is defined in the method's scope:

interface Printer {
  void print(String msg);
}
class Main {
  public static void main(String[] args) {
    String msg = "Hello";

    // A compile-time error. 
    Printer printer = msg -> System.out.println(msg);
  }
}

The following code generates a compile-time error since the local variable name msg is in scope inside the body of the lambda expression.

class Test {
  public static void main(String[] args) {
    String msg = "Hello";

    Printer printer = msg1 -> {
      String msg = "Hi"; // A compile-time error
      System.out.println(msg1);
    };
  }
}

Related Topic