Groovy #3

Multiple return values from a method

One of the nicer features of Groovy is the ability to return multiple return values from a method via an implicit List and mapping them automatically to variables in the same order.

While iterator methods are very useful in Groovy, you have access only to the current “it” object within an iterator closure. There are times you may need access to a previous and next values too, just like in a Doubly LinkedList. Here is a smart closure that demonstrates meta programming technique (ie dynamically adding a method to java.util.List), multi-return values and iterators.


//create a [prev,current,next] list triplet from an array
List.metaClass.triplet = { i -> delegate.size() <= 0 ? [null,null,null] : i == 0 ? [null, delegate[i], (delegate.size()>1) ? delegate[i+1] : null] : (i==delegate.size()) ? [(i<1) ? null : delegate[i-1]] : [delegate[i-1], delegate[i], delegate[i+1]] }

Usage:


def list = [1,2,3,4,5,6,7,8,9,10]
for (int i=0; i<list.size(); i++) {
def (prev, current, next) = list.triplet(i)
}

This will print the following output:


[null,1,2]
[1,2,3]
...
[9,10,null]

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: