我想定义一个接受一个参数的闭包(我用 it
指代)
有时我想向闭包传递另一个额外的参数。
我怎样才能做到这一点?
最佳答案
您可以将第二个参数设置为默认值(例如 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
另一种选择是制作
b
像这样的可变参数列表: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
关于带有 optional 参数的 Groovy 闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12580262/