Custom collections in Groovy

Groovy allows to create custom collections the easy way. Moreover, a custom collection can support the Groovy collection API (all the additional methods that Groovy adds to Collection/List/Set).

The implementation is simple. Your custom collection is a decorator over the original collection. You provide a constructor accepting the collection you are wrapping. All method calls are delegated to the original collection with @Delegate annotation.

As an example, a custom list of Strings:

How to create your collection? You don’t have to call the constructor explicitly. Groovy as operator comes to the rescue:

Let’s see if it works:

Everything perfect!

For the curious, the culprit is DefaultGroovyMethods.asType(Collection col, Class clazz) method. It allows to cast plain Groovy collection to a custom implementation by calling the wrapping constructor.

Advertisements