An extension for Groovy Lists – a less strict alternative for first(), last(), etc.

A follow-on from my earlier post An extension for Groovy Lists – getting the only element of a List

A common use case (for me, at least)

I have often found myself with cases where I want to try to get an element from a list knowing that the later code will behave as expected, regardless of whether the element was present or not. An example of this:

if (!playersStillToPlay.isEmpty()) {
    currentPlayer = playersStillToPlay.head()
    playersStillToPlay = playersStillToPlay.tail()
}
else {
    currentPlayer = null  // Needs to be null if playersStillToPlay was an empty list
                          // If playersStillToPlay was empty it doesn't matter what playersStillToPlay is after this point so I don't change it
}

if (currentPlayer) {
    // Do the things
    // Use value of playersStillToPlay
}

To suit this type of situation I wanted versions of first(), last(), etc. which were Continue reading

An extension for Groovy Lists – getting the only element of a list

This is the first post about an extension library I wrote for use in Groovy projects.

A little background

Groovy is a programming language which runs on the JVM (Java Virtual Machine). Any computer or device that can run Java programs can also run programs written in Groovy and it enhances the Java programming language in many ways. I won’t go into them all here but for anyone who develops in Java I would recommend checking it out for its expressiveness, power, and speed of development.

In version 2 of Groovy there is a new mechanism for adding extensions to pre-existing classes. Groovy uses the same mechanism to extend some of Java’s classes. This is the mechanism I used to write my extensions library. You can find more information at http://groovy.codehaus.org/Groovy+2.0+release+notes#Groovy2.0releasenotes-Extensionmodules. I used Tim Yatesgroovy-common-extensions library as an example of this sort of extension library and based some of my build code from there. It has some interesting extensions itself and is worth checking out.

Groovy Lists

One of the features Groovy provides is a number of extensions to many of the common Java classes and interfaces. For example the List class has been given the Continue reading