Vuk Djapic Vuk Djapic - 2 months ago 6
Groovy Question

Usage of parentheses in Groovy method call

I started learning Groovy, and understood that parentheses are optional in method calls, so

def list = [0, 1, 2, 3]
list.each ({ item ->
println "Item: $item"
})


is the same as

def list = [0, 1, 2, 3]
list.each { item ->
println "Item: $item"
}


But now found this example

def list = [0, 1, 2, 3]
list.each() { item ->
println "Item: $item"
}


which also works. How is it possible to first call method with empty parameter list, and then specify closure after it?

Answer

Things are a little different when closures are involved. There is a special facility for closures that occur as the last parameter (as explained here).

As another illustration, consider:

class Foo {
    int bar(s, c) {
        return c(s)
    }

    int abc(c, s) {
        return c(s)
    }
}

def foo = new Foo()
def s = "fox"

This is a classic style:

assert 3 == foo.bar(s, { it.size() })

Yet this will work for closures as last argument:

assert 3 == foo.bar(s) { it.size() }

This is classic:

assert 3 == foo.abc({ it.size() }, s)

But this won't work

// assert 3 == foo.abc({ it.size() }) s

No doubt the reasoning is that if there is only one parameter, as with List.each(), then the syntax is very elegant:

list.each { item -> println item }
Comments