Take the 2-minute tour ×

Groovy noob here, I'm working through my first Groovy book and it has example code where it states roughly

"If I want a property to be a ready-only property then declare it final. This is not defining a final field but a read-only property-you can change the property from within instance methods of the defining class, but not from outside"

Here is the code I have in question, but I keep getting an error stating:

cannot modify final field 'miles' outside of constructor.


class Car
    final miles = 0

    def getMiles()
        println "getMiles called"

    def drive(dist){if (dist>0) miles += dist }


The book says I should be able to modify miles from within the drive instance method, am I doing something wrong?

share|improve this question
I am working through the same book and wrote the same code and was given this issue, thanks for posting! –  ericraio Dec 15 '13 at 18:10

1 Answer 1

up vote 2 down vote accepted

I think what they meant (not sure what they said, if you're paraphrasing) is that there's no setter method defined, so it can't be modified from outside the class.

It is, however, still a final property, which means it can't be modified once its set, which would be in a constructor or during the declaration.

Property and field rules

That said, see these two issues: 1628, 2752, so more exploration might be necessary, although this appears limited to local script properties.

My guess is you're using a 1.7+ Groovy, while the book targets <= 1.6.

See also this SO question.

share|improve this answer
can I declare something like: def final miles? –  ProfessionalAmateur Nov 13 '11 at 0:59
That question you reference speaks about same book and chapter I am on. Looks like the book was written for <1.6 and Im using 1.8 to play with. –  ProfessionalAmateur Nov 13 '11 at 1:09
@ProfessionalAmateur Yep; they fixed it (although it took a year or two!) –  Dave Newton Nov 13 '11 at 1:16

Your Answer


