Java Reference
In-Depth Information
Ask the Expert
Q :
In addition to variable initialization, assignment, and argument passing, what
other places constitute a target type context for a lambda expression?
A : Casts, the ? operator, array initializers, return statements, and lambda expressions,
themselves, can also serve as target type contexts.
Lambda Expressions and Variable Capture
Variables defined by the enclosing scope of a lambda expression are accessible within the
lambda expression. For example, a lambda expression can use an instance variable or stat-
ic variable defined by its enclosing class. A lambda expression also has access to this (both
explicitly and implicitly), which refers to the invoking instance of the lambda expression's
enclosing class. Thus, a lambda expression can obtain or set the value of an instance vari-
able or static variable and call a method defined by its enclosing class.
However, when a lambda expression uses a local variable from its enclosing scope, a
special situation is created that is referred to as a variable capture . In this case, a lambda
expression may only use local variables that are effectively final . An effectively final vari-
able is one whose value does not change after it is first assigned. There is no need to ex-
plicitly declare such a variable as final , although doing so would not be an error. (The this
parameter of an enclosing scope is automatically effectively final, and lambda expressions
do not have a this of their own.)
It is important to understand that a local variable of the enclosing scope cannot be mod-
ified by the lambda expression. Doing so would remove its effectively final status, thus
rendering it illegal for capture.
The following program illustrates the difference between effectively final and mutable
local variables:
Search WWH ::




Custom Search