Lambda expression limitations
There are two aspects of a Lambda expression that we would like to point out and clarify:
- If a Lambda expression uses a local variable created outside it, this local variable has to be final or effectively final (not reassigned in the same context).
- The
this
keyword in a Lambda expression refers to the enclosing context, not the Lambda expression itself.
As in an anonymous
class, the variable created outside and used inside a Lambda expression becomes effectively final and cannot be modified. The following is an example of an error caused by the attempt to change the value of an initialized variable:
int x = 7;
//x = 3; //compilation error
Function<Integer, Integer> multiply = i -> i * x;
The reason for this restriction is that a function can be passed around and executed in different contexts (different threads, for example), and an attempt to synchronize these contexts would defeat the original idea of the stateless...