Sobes.tech
Junior — Middle

Kas lambdaavaldis saab ligi pääseda meetodi sees deklareeritud muutujale, milles see on määratletud?

sobes.tech AI

Vastus AI-lt

In Java, a lambda expression can access a local variable declared in the method only if that variable is effectively final. This means that after initialization, the value of the variable does not change.

Example:

public void example() {
    int number = 10; // effectively final variable
    Runnable r = () -> System.out.println(number);
    r.run();
}

Trying to modify number after the lambda is defined will result in a compile-time error.

This restriction is related to the fact that the lambda may be executed later, and to avoid issues with mutable state, Java requires such variables to be immutable.