Search code examples
groovyconstructorinitializationfinal

Why can't I initialize a final class variable via a closure inside the constructor in Groovy?


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

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 it a difference whether I initialize the final variable inside a closure, or at the top-level of the constructor?


Solution

  • Can any one explain to me why the below code works if final is commented out, but not if final is present?

    The compiler has to enforce that your final properties are initialized in the constructor and there is no way to do that in your example because the compiler doesn't know what will be in the Map.