Dark theme | Light theme

November 12, 2009

Groovy Goodness: Passing Closures to Methods

Closures are blocks of code we can assign to variables and pass around like objects. We can use closures as method arguments, but we must make sure we use the correct syntax. Groovy has some variations we can use to pass a closure into a method. If for example the closure is the last argument for a method we can put the closure outside the argument list.

// Method with two arguments. Last argument is a closure.
def work(input, cl) {

// Define a closure.
def assertJava = {
    it == 'Java'

work('Java', assertJava)

work 'Java', assertJava  // No parenthesis.

work('Groovy', {
    assert it == 'Groovy' 
})  // Anonymous closure as argument.

work('Groovy') {
    assert it == 'Groovy'
}  // Last argument is closure and can be outside parenthesis.

     assert it == 'Groovy'
}  // Opening bracket on new line. If we want a code block (e.g. static initializer) instead of closure we must use ; to separate code.

work 'Groovy', {
    assert it == 'Groovy'
}  // Pay attention, no parenthesis, so comma is needed again!

// Does not work:
// Comma between argument list needed:
// work 'Groovy' {
//     assert it == 'Groovy'
// }