刚开始学习Groovy,得到了PragProg的书"Programming Groovy",并且在编译其中一个示例脚本时遇到了问题:
class GCar2 {
final miles = 0
def getMiles() {
println "getMiles called"
miles
}
def drive(dist) {
if (dist > 0) {
miles += dist
}
}
}
def car = new GCar2()
println "Miles: $car.miles"
println 'Driving'
car.drive(10)
println "Miles: $car.miles"
try {
print 'Can I see the miles? '
car.miles = 12
} catch (groovy.lang.ReadOnlyPropertyException ex) {
println ex.message
Run Code Online (Sandbox Code Playgroud)
GroovyCar2.groovy: 20: cannnot access final field or property outside of constructor.
@ line 20, column 35.
def drive(dist) { if (dist > 0) miles += dist }
^
Run Code Online (Sandbox Code Playgroud)
1.7之前的Groovy版本不会出错.我查看了我能找到的任何文档,但没有看到讨论的问题.这里发生了什么?
亚伦
我不太了解Groovy 1.7,但它看起来像早期版本中的一个错误,现在已经修复 - 如果变量是最终的,你不应该在构造函数(或它的声明)之外分配它.如果可以的话,最终成功的重点是什么?
我怀疑它会阻止你在构造函数之外阅读它...
| 归档时间: |
|
| 查看次数: |
2077 次 |
| 最近记录: |