Lambdas and variable scope
Sooner or later when programming with lambdas, we hit upon the following question:
which fields or variables can we access from a lambda expression? The simple answer is that
accessibility is similar to that of anonymous inner classes. Lambdas generally share or "capture" the scope of
the code that calls it. This means that:
- any fields that were accessible to the code calling the lambda expression are accessible
within the lambda expression;
- any local variables accessible to the caller are accessible from within the
lambda expression provided that they are em>effectively final (i.e. assigned to exactly
once before the lambda expression is called);
- local variables therefore cannot be modified from within a lambda expression;
- data accessed via final local references can be modified (either accidentally or deliberately!).
However, they differ from anonymous inner classes in their naming scope. Specifically:
-
this
refers to the same object inside the lambda as it did outside of the lambda.
(The same therefore applies to super
.)
Apart from the last rule, most rules about variable name scope and field and variable access from within lambdas
will seem intuitive if you are used to programming with anonymous inner classes. In addition, if you are
programming with a good IDE, it will generally help you when you go wrong!
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.