Loading...

Saturday, November 28, 2009

Groovy Goodness: Closure Arguments

If we define a closure in Groovy we can define our own arguments or rely on the default it for a single argument closure. The it argument is available if we don't define any named arguments ourselves. We can also create a closure and define it to have no arguments even not the it argument.

// Closure with default 'it' argument.
def defaultIt = { it - 1 }
assert 'Groovy String with .' == defaultIt('Groovy String with 1.')
assert 41 == defaultIt(42)

// Closure with named argument.
def namedArg = { value -> value * 2 }
assert 'Groovy Groovy ' == namedArg('Groovy ')
assert 84 == namedArg(42)

// Closure with multiple named arguments.
def moreArgs = { a, b -> a + b }
assert 'Groovy Java' == moreArgs('Groovy ', 'Java')
assert 44 == moreArgs(42, 2)

// Closure without arguments, even no 'it'.
def noArgs = {-> 'Groovy closure without arguments' }
assert 'Groovy closure without arguments' == noArgs()

2 comments:

Steve said...

I don't think you need the -> in the last example with no args.

Steve said...

Ah ha! The last line here fails:

def a = {'123'}
def b = {->'123'}
assert '123' == a()
assert '123' == a('456')
assert '123' == b()
assert '123' == b('456') //ka-boom!

I think closure "a" must assign the optional parameter 'it' to itself, whereas "b" does not.

Very interesting.

Post a Comment