Groovy 1.7改变“最终”? [英] Groovy 1.7 changes "final"?

查看:86
本文介绍了Groovy 1.7改变“最终”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始学习Groovy,得到了PragProg书籍Programming Groovy,并且编译了一个示例脚本时遇到了问题:

Just started learning Groovy, got the PragProg book "Programming Groovy" and had a problem compiling one of the sample scripts:

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







GroovyCar2.groovy: 20: cannnot access final field or property outside of constructor.
 @ line 20, column 35.
     def drive(dist) { if (dist > 0) miles += dist }
                                     ^






Groovy版本在1.7之前不会给出错误。我浏览了我能找到的任何文档,并没有看到讨论的问题。这是怎么回事?


Groovy versions prior to 1.7 do not give an error. I looked through whatever documentation I could find and did not see the issue discussed. What is going on here?

Aaron

推荐答案

对Groovy 1.7了解很多,但它看起来像早期版本中的一个bug,现在已经修复了 - 如果一个变量是最终的,你不应该在构造函数(或其声明)之外赋值它。如果可以的话,有什么意义可以让它最终成功?

I don't know much about Groovy 1.7, but it looks like a bug in earlier versions which has now been fixed - if a variable is final, you shouldn't be able to assign to it outside the constructor (or its declaration). If you can, what's the point of making it final?

我怀疑它会阻止你从构造函数之外读它。 ..

I doubt that it'll stop you from reading it outside the constructor though...

这篇关于Groovy 1.7改变“最终”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆