I want to define a closure which takes one argument (which i refer to with it
)
sometimes i want to pass another additional argument to the closure.
how can i do this?
You could set the second argument to a default value (such as null):
def cl = { a, b=null ->
if( b != null ) {
print "Passed $b then "
}
println "Called with $a"
}
cl( 'Tim' ) // prints 'Called with Tim'
cl( 'Tim', 'Yates' ) // prints 'Passed Yates then Called with Tim
Another option would be to make b
a vararg List like so:
def cl = { a, ...b ->
if( b ) {
print "Passed $b then "
}
println "Called with $a"
}
cl( 'Tim' ) // prints 'Called with Tim'
cl( 'Tim', 'Yates' ) // prints 'Passed [Yates] then Called with Tim
cl( 'Tim', 'Yates', 'Groovy' ) // prints 'Passed [Yates, Groovy] then Called with Tim