为什么我不能通过 Groovy 中构造函数中的闭包来初始化最终的 class 变量?
Why can't I initialize a final class variable via a closure inside the constructor in Groovy?
任何人都可以向我解释为什么下面的代码在 final
被注释掉时有效,但如果 final
存在则无效?
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
换句话说,为什么我在闭包内或在构造函数的顶层初始化 final 变量是不同的?
Can any one explain to me why the below code works if final is
commented out, but not if final is present?
编译器必须强制在构造函数中初始化您的最终属性,但在您的示例中无法做到这一点,因为编译器不知道 Map
.
任何人都可以向我解释为什么下面的代码在 final
被注释掉时有效,但如果 final
存在则无效?
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
换句话说,为什么我在闭包内或在构造函数的顶层初始化 final 变量是不同的?
Can any one explain to me why the below code works if final is commented out, but not if final is present?
编译器必须强制在构造函数中初始化您的最终属性,但在您的示例中无法做到这一点,因为编译器不知道 Map
.