Simple Groovy-isms

You learn pretty quick when switching over from Java to Groovy. Problem is that it is fairly backwards compatible, so if you aren’t doing something in the easiest way possible, it may be hard to know. For the basics, I just want to state them so that everybody is at least covering the basics.

Scoping

By default, classes are public in groovy. Don’t add the public keyword. Similarly, member variables are private. The accessors and mutators are generated (as you’ll see in the next section).

Accessors and Mutators

Accessors should be adjusted from

To the following

Similarly, the mutator

should be used as follows

It looks like you are accessing the private method, but it’s not. It’s just shorthand for calling the “get” function. This is important because even if there is no member variable – such as x.getCount(), this should still be called using x.count. That’s one of the fun shortcuts in Groovy. Continue reading

Groovy Scripting or Gradle – check if binding variable (or Gradle property) is defined

In scripting, its helpful to create global variables.  It’s definitely not a good idea for any form of scalability, obviously, but Groovy has done a good job in creating this slight separation of function.

The difference is that the following won’t work:

but the following will work:

This can cause some problems in scripting if you need to either provide default values or if you need it to provide a better exception if the variable isn’t found. Continue reading