Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

As a Java developer embarks on a Groovy adventure, he/she always has Java in mind, and progressively learn Groovy, a feature at a time, making him more productive and writing more idiomatic Groovy code. This document's purpose is to guide such a developer along the way, learning some common Groovy syntax style, learning new operators, new features like closures, etc. This guide is by no means extensive, but only serve as a quick intro, and a base for further guideline sections, should you feel like contributing to the document and enhance it.

No semicolons

When coming from a C / C++ / C# / Java background, we're so used to semicolons, that we put them everywhere. Even worse, Groovy supports 99% of Java's syntax, and sometimes, it's so easy to paste some Java code into your Groovy programs, and you end up with tons of semicolons everywhere. But... semicolons are optional in Groovy, you can omit them, and it's more idiomatic to remove them.

Return keyword optional

In Groovy, the last expression evaluated in the body of a method can be returned without necessiting the 'return' keyword. specially for short methods and for closures, it's nicer to omit it for brevity:

But sometimes, this doesn't look to good when you're using a variable, and see it visually twice on two rows:

In such case, either putting a newline before the last expression, or explicitely using 'return' may yield better readability.

I, for myself, sometimes use the return keyword, sometimes not, it's often a matter of taste. But often, inside of closure, we omit it more often than not, for example. So even if the keyword is optional, this is by no means mandatory to not use it if you think it halters the readability of your code.

A word of caution, however. When using methods which are defined with the 'def' keyword instead of a specific concrete type, you may be surprise to see the last expression being returned sometimes. So usually prefer using a specific return type like void or a type.
In our example above, imagine we forgot to put m2 as last statement to be returned, the last expression would be m2.c = 3, which would return... 3, and not the map you expect.

Def and type

As we're talking about def and types, I often see developers using both 'def' and a type.
But 'def' is redundant here. So make a choice, either use 'def' or a type.

So don't write:


Public by default

By default, Groovy considers classes and methods 'public'. So you don't have to use the 'public' modifier everywhere something is public. Only if it's not public, you should put a visibility modifier.

So instead of:

Prefer the more concise:

You may wonder about the 'package-scope' visibility, and the fact Groovy allows one to omit 'public' means that this scope is not supported by default, but there's actually a special Groovy annotation which allows you to use that visibility:

Omitting parentheses

Groovy allows you to omit the parentheses for top-level expressions, like with the println command:


When a closure is the last parameter of a method call, like when using Groovy's 'each‘ iteration mechanism, you can put the closure outside the closing parens, and even omit the parentheses:

Always prefer the third form, which is more natural, as an empty pair of parentheses is just useless syntactical noise!

Classes as first-class citizens

The .class suffix is not needed in Groovy, a bit like in Java's instanceof.

For example:

Using GStrings we're going to cover below, and using first class citizens:

Getters and Setters

In Groovy, a getters and setters form what we call a "property", and offers a shortcut notation for accessing and setting such properties. So instead of the Java-way of calling getters / setters, you can use a field-like access notation:

When writing your beans in Groovy, often called POGOs (Plain Old Groovy Objects), you don't have to create the field and getter / setter yourself, but let the Groovy compiler do it for you.

So instead of:

You can simply write:

As you can see, a free standing 'field' without modifier visibility actually makes the Groovy compiler to generate a private field and a getter and setter for you.

When using such POGOs from Java, the getter and setter are indeed their, and can be used as usual, of course.

Initializing beans with named parameters and the default constructor

With a bean like:

Instead of setting each setter in subsequent statements as follows:

You can use named parameters with the default constructor (first the constructor is called, then the setters are called in turn):

Using with() for repeated operations on the same bean

Named-parameters with the default constructor is interesting when creating new instances, but what if you are updating an instance that was given to you, do you have to repeat the 'server' prefix again and again? No, thanks to the with() method that Groovy adds on all objects of any kind:


Equals and ==

Java's == is actually Groovy's is() method, and Groovy's == is a clever equals()!
To compare the references of primitives, instead of ==, you should use
But to do the usual equals() comparison, you should prefer Groovy's ==, as it also takes care of avoiding NullPointerException, independently of whether the left or right is null or not.

Instead of:


GStrings (interpolation, multiline)

We often use string and variable concatenation in Java, with many opening / closing of double quotes, plus signs, and \n characters for newlines. With interpolated strings (called GStrings), such strings look better and are less painful to type:


Inside the curly braces, you can put any kind of expression, not just variables. For simple variables, or, you can even drop the curly braces:

You can even lazily evaluate those expressions using a closure notation with ${-> resource }.

When strings and their concatenated expression are long in Java:

You can use the \ continuation character (this is not a multiline string):

Or using multiline strings with triple quotes:

You can also strip the indentation appearing on the left side of the multiline strings by calling .stripIndent() on that string.

Also note the difference between single quotes and double quotes in Groovy: single quotes always create Java Strings, without interpolation of variables, whereas double quotes either create Java Strings or GStrings when interpolated variables are present.

For multiline strings, you can triple the quotes: ie. triple double quotes for GStrings and triple single quotes for mere Strings.

Native syntax for data structures

Groovy provides native syntax constructs for data structures like lists, maps, regex, or ranges of values. Make sure to leverage them in your Groovy programs.

Here are some examples of those native constructs:

The Groovy Development Kit

Continuing on the data structures, when you need to iterate over collections, Groovy provides various additional methods, decorating Java's core data structures, like each{}, find{}, findAll{}, every{}, collect{}, inject{}. These methods add a functional flavor to the programming language and help working with complex algorithms more easily. Lots of new methods are applied to various types, through decoration, thanks to the dynamic nature of the language. You can find lots of very useful methods on String, Files, Streams, Collections, and much more:

The power of switch

Groovy's switch are much more powerful than in C-ish languages which usually only accept primitives and assimilated. Groovy's switch accepts pretty much kind of type.

And more generally, types with an isCase() method can also decide whether a value corresponds with a case

Import aliasing

In Java, when using two classes of the same name but from different packages, like java.util.List and java.awt.List, you can import one class, but have to use a fully-qualified name for the other.

Also sometimes, in your code, when using often a long class name, and the code becomes a bit more verbose.

To improve such situations, Groovy features import aliasing:

Groovy Truth

All objects can be 'coerced' to a boolean value: everything that's null, void or empty evaluates to false, and if not, evaluates to true.
So instead of writing if (name != null && name.length > 0) {}, you can just do if (name) {}. Same thing for collections, etc.
Thus, you can use some shorcuts in things like while(), if(), the ternary operator, the Elvis operator (see below), etc.

It's even possible to customize the Groovy Truth, by adding an boolean asBoolean() method to your classes!

Safe graph navigation

Groovy supports a variant of the . operator to safely navigate an object graph.
In Java, when you're interested in a node deep in the graph and need to check for null, you often end up writing complex if, or nested if statements like this:

With ?. safe dereference operator, you can simplify such code with:

Nulls are checked throughout the call chain and no NullPointerException will be thrown if any element is null, and the resulting value will be null if something's null.


To check your parameters, your return values, and more, you can use the 'assert' statement.
Contrary to Java's assert, asserts don't need to be activated to be working, so asserts are always checked.

You'll also notice the nice output that Groovy's "Power Assert" statement provides, with a graph view of the various values of each sub-expressions being asserted.

Elvis operator for default values

The Elvis operator is a special ternary operator shortcut which is handy to use for default values.
We often have to write code like:

Thanks to Groovy Truth, the null check can be simplified to just 'name'.
And to go even further, since you return 'name' anyway, instead of repeating name twice in this ternary expression, we can somehow remove what's in between the question mark and colon, by using the Elvis operator, so that the above becomes:

Catch any exception

If you don't really care of the exception which are thrown inside your try block, you can simply catch any of them and simply omit the type of the caught exception. So instead of catching the throwables like in:

Then catch anything ('any' or 'all', or whatever makes you think it's anything):

Optional typing advice

I'll finish on some words on when and how to use optional typing. Groovy lets you decide whether you use explicit strong typing, or when you use 'def'.

I've got a rather simple rule of thumb: whenever the code you're writing is going to be used by others as a public API, you should always favor the use of strong typing, it helps making the contract stronger, avoids possible passed arguments type mistakes, gives better documentation, and also helps the IDE with code completion whenever the code is for your use only, like private methods, or when the IDE can easily infer the type, then you're more free to decide when to type or not

  • No labels