Showing posts with label count me in. Show all posts
Showing posts with label count me in. Show all posts

Tuesday, August 25, 2009

An Understated Feature in Groovy

Background

I have worked with Groovy for awhile, but have been averse to one feature: the implicit return of the last expression evaluated. For example:


def getFoo() {
def foo = null

if (something) {
foo = new Foo()
}

foo // no 'return' necessary
}

In the above code, I would use return because it felt safer to me. I tended to agree with Eric's post (with respect to explicit returns).

Revelation

I get it now, and it's all thanks to the enhanced collection methods in Groovy.

Consider the collect method. It transforms a list by applying a function. In pseudocode:


[ a, b, c, d] => [ f(a), f(b), f(c), f(d) ]

With that in mind, here's another example:


class Composer {
def name
// def era, etc
}

def list = [ 'Bach', 'Beethoven', 'Brahms' ]

// the closure returns the new Composer object, as it is the last
// expression evaluated.

def composers = list.collect { item -> new Composer(name : item) }

assert 'Bach' == composers[0].name

The idea is simply to build a list of Composer objects from a list of strings. As noted in the comment, the closure passed to collect uses the implicit return to great effect. At one time, I would have taken 3-4 lines to express that idea.

But now, this code is not merely concise: it is truly elegant. Very reminiscent of other languages such as Python.

The Take-Home Message

There are many lists of excellent Groovy features. However we rarely see 'implicit return' listed. I'm a fan: it greases the wheels for other features.

I realize it is available in many languages: I just haven't used it in Groovy. I suspect in a few weeks I won't be able to live without it.