April 27, 2011

Groovy Goodness: Chain Closures Together with Closure Composition

There are a lot of new features in Groovy 1.8. One of them is the possibility to compose a new closure by chaining two other closures together. We use the leftShift and rightShift operators (<< and >>) to combine multiple closures to create a new closure.

def convert = { new Expando(language: it) }
def upper = { it.toUpperCase() }

// Composition.
def upperConvert = convert << upper

def languages = ['Groovy', 'Scala', 'Clojure'].collect(upperConvert)
println languages // Output: [{language=GROOVY}, {language=SCALA}, {language=CLOJURE}]
assert languages[0].language == 'GROOVY'
assert languages[1].language == 'SCALA'
assert languages[2].language == 'CLOJURE'

// Reverse composition.
def lastLetter = { it[-1] }
def firstLetters = ['Groovy', 'Clojure', 'Scala'].collect(upper >> lastLetter)
assert firstLetters.join() == 'YEA'

Try with Groovy web console.