Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy 1.7 changes "final"?

Tags:

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

like image 752
acarlow Avatar asked Dec 29 '22 15:12

acarlow


1 Answers

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

like image 195
Jon Skeet Avatar answered Dec 31 '22 05:12

Jon Skeet