Wednesday, February 23rd, 2011

“Stealth” Groovy Methods

Groovy has a number of simple and useful methods that are almost impossible to find by a web search. Try as you wish, googling for any, find, or count just gets you a giant haystack hiding the proverbial buried needle. And... hey, what was the name of that method that lets you insert a value into an iteration, kind of?

This post is about those Groovy methods that are all over the place, and yet hard to find. I wrote it as a reminder to myself.

First of all, the key to many "stealth" methods is the class org.codehaus.groovy.runtime.DefaultGroovyMethods. It's in the API docs (not to be confused with the GAPI or Groovy-JDK docs). It's a treasure trove of Groovy goodies. Make sure you browse the documentation of this class now and then. You will almost certainly be reminded of useful stuff or learn something new. Just keep in mind that there is syntactic sugar for some of them. For instance, the getAt method can be invoked with the "[]" syntax. Invoking by name is completely legal, but not as elegant.

Unfortunately there are missing pieces in the documentation. For instance, if a method takes a closure argument, the arguments of that closure may be undocumented.

To spare you haystack time, let's dive into some code.

inject & co
The inject method is useful to compute a single value from a collection or an array. The argument is passed ("injected") into the first iteration. The value returned by an iteration is passed into the subsequent iteration, or returned as the result at the end of iteration.

The second argument is a closure that takes the following arguments,

  1. The injected value
  2. The iteration item

The following example begins with an anti-pattern to avoid, followed by the Groovy way. The Groovy way happens to coincide with functional programming style.


  1. span style="color: #808080; font-style: italic;">// Anti-pattern to avoid
  2. // inject: the Groovy way
  3. // join: a special case
  4. ':') == '1:2:3:4:5'
  6. // find: single out an item
  7. // This example finds the first even number
  8. // find: may return nothing (i.e. null)

The join method is included in the example above. It is almost a special case of inject. It appends the toString images of the iteration values.

The find method is also included. It doesn't do any aggregation. It just finds an element matching a condition, or returns null. Groovy Truth applies, as the next example shows.


  1. // find: uses Groovy Truth
  2. '''hi''hi'

Learn the inject method and its cousins, join and find. They make your code more readable, more functional, and hence more robust.

Comments are closed.