开发者

Groovy 1.7 changes "final"?

Just starte开发者_运维知识库d 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 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


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...


You shouldn't be able to assign to a final variable in a normal method. It was a bug in groovy, fixed in 1.7.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜