Sobes.tech
Senior

To which objects can you refer inside a lambda?

sobes.tech AI

Answer from AI

Inside a lambda expression in Java, you can access:

  • Local variables, but only if they are effectively final (meaning they are not modified after initialization).
  • Fields and methods of the outer class (including non-static ones), as the lambda captures a reference to the outer class object.
  • Parameters of the method in which the lambda is declared, provided they are also effectively final.

Example:

int number = 10; // effectively final
Runnable r = () -> {
    System.out.println(number); // can be used
    System.out.println(this.toString()); // access to outer class methods and fields
};
r.run();

Trying to modify a local variable after it has been used in a lambda will result in a compile-time error.