I’m on a Groovy buzz at the moment. I figured that I’d learn the language properly rather than poking around, doing stuff in Grails. It’s one of Groovy’s huge advantages that you can hack away as a Java programmer and be fairly productive. So playing with properties:
class Thingo { def value def anotherValue void setValue(Integer value) { this.value = value * 2 } } thingo = new Thingo(value: 3); println thingo.value thingo.value = 2 println thingo.value thingo.anotherValue = 2 println thingo.anotherValue
The results:
6 4 2
A few things are going on here:
- When we construct our Thingo in the script above, Groovy calls the default constructor, and immediately updates value. As a setter method has been defined “setValue()”, Groovy does not generate a default one and uses what’s there -the one we’re using to encapsulate some programmer-defined variable fiddling.
- Likewise, when we assign a variable to value, Groovy makes use of our setter to update value.
- When we assign a number to anotherValue, a default setter is created at runtime and is used to perform the update.
I’m really enjoying the benefit of the groovyConsole – it lets you mess around with code really easily, without needing to even save it. Low-ceremony programming at it’s best.
If you’re looking at learning Groovy properly, I strongly recommed Programming Groovy by Venkat Subramaniam. Just like the language itself, it gets you doing stuff very quickly.