Why can't I initialize the last class variable through closure inside the constructor in Groovy?

Can someone explain to me why the code below works if finalcommented out, but not if finalpresent?

public class Person {
    public /*final*/ String firstName, lastName

    Person(Map parameters) {
        // This does *not* work with "final":
        parameters.each { name, value ->
            this."$name" = value
        }

        // This *does* work with "final":
        this.lastName = parameters['lastName']
    }
}

Person p = new Person(firstName: 'Joe', lastName: 'Doe')
println p.firstName + ' ' + p.lastName

In other words, why is the difference whether I initialize the final variable inside the closure or at the top level of the constructor?

+4
source share
1 answer

Can someone explain to me why the code below works if the final one has commented, but not if the final one is present?

, , , , Map.

+3

Source: https://habr.com/ru/post/1612612/


All Articles