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:

However, they differ from anonymous inner classes in their naming scope. Specifically:

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.