1

Variables in lambda`s must be effectively final. Ok. But why it is allowed to assign class field value in example code below?

Does heap and stack cause this difference? Why?

class Scratch
{
    public String field = "class field";


    public void example()
    {
        Function<String, Integer> funcWithField = s ->
        {
            field = "New field value from lambda";
            // IT`s OK here
            return field.length();
        };

        String variable = "var";
        Function<String, Integer> funcWithVariable = s ->
        {
            // Though such things are restricted!
            // variable = "some other loooong value for variable";
            return variable.length();
        };
    }
}
2
  • Here's my "off the hip" explanation (not sure if it's totally correct): The lambda using the field will capture the class instance in its closure. You can't do it with a local variable, because the closure can't capture the scope. Commented Feb 12, 2019 at 15:25
  • "You are only able to modify local variables within a local scope". This was true before lambdas. Multi-threading lambdas are changing the game and to keep the statement about local variables true, the final-restriction has been added for local variables which participate in lamda code. Class attributes have never had this "local scope" issue, hence no additional restrictions have been added here. Commented Feb 12, 2019 at 15:58

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.