Lambda expressions do not introduce any new naming environment. Names in the body of a lambda are interpreted exactly as in the enclosing environment, except for the addition of new names for the lambda expression’s formal parameters. The keywords this
and super
also have the same meaning as immediately outside the lambda expression—that is, they refer to the enclosing class. Formal parameters follow the same rules as method parameters for shadowing class and instance variables. For example, the declaration of Bar:
class Bar { int i; Foo foo = i -> i * 2; };
is legal because the lambda parameter i
shadows the instance variable. For local variables, on the other hand, shadowing is not possible, so the variable is not redeclared and the usual rule of assignment before use applies, making the method declaration
void bar() { int i; Foo foo = i -> i * 2; }; // Illegal: variable i is already defined
illegal.
Leave a Reply