December 11, 2010

Groovy Goodness: Find First Non-Null Result From a Closure

A new feature from Groovy 1.8 (according to the Javadoc it is available since 1.8) is already available in Groovy 1.7.5. With the method findResult() we iterate through an object and find the first non-null result from a closure. We can even define a default value if there is no non-null result.

def list = ['Groovy', 'Griffon', 'Grails', 'Gradle']

assert list.findResult { it.startsWith('Gra') ? it : null } == 'Grails'
assert list.findResult('Gr8') { 
    if (it.size() < 6) {
        "found text with size smaller than 6"
} == 'Gr8'