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:
https://gist.github.com/mgryszko/4dc9529dcf38b352f545

How to create your collection? You don’t have to call the constructor explicitly. Groovy as operator comes to the rescue:
https://gist.github.com/mgryszko/51eeff395b40e2d3f664

Let’s see if it works:
https://gist.github.com/mgryszko/e59e8597837063ba50a1

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.