Loading...

December 1, 2010

Groovy Goodness: Invoke Anonymous Closure

Groovy closures can be invoked directly after we have defined them. This way we get the result immediately and can assign it to a variable. We use call() or () after we have defined the closure, so the closure code is executed and the return value of the closure is assigned to the variable.

def date = {
    def d = new Date()
    d.set year: 2010, month: Calendar.DECEMBER, date: 1
    d.format "dd-MM-yyyy"
}()

assert date == '01-12-2010'

def text = {
    def result = ''
    "mrhaki".size().times {
        result += it
    }
    result
}.call()

assert text == '012345'