How not to add a non-empty item to a list in Groovy

In our code, a colleague (Alard), found the following piece of code in our Grails codebase:

I think the intention of this code is clear (in case of ‘false’ items, add a empty String’), but the outcome was surprising. Take 5 seconds and guess the output of line 4, then read on.

As you might have guessed, the outcome isn’t a list with an empty String (which is displayed as a empty list, but that’s a different story). The outcome of the above is:


That is because the Groovy << operator has precedence over the ?: operator. In code, it's as if the following had been written:

Which makes it obvious: the item is always added to the list, and the empty String is ignored. Fixing this is easy: just add some clarifying braces: