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();
        };
    }
}
Boris
  • 27
  • 3
  • 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. – marstran Feb 12 '19 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. – Mick Feb 12 '19 at 15:58

0 Answers0