带可选参数的Groovy闭包 [英] Groovy Closure with optional arguments
本文介绍了带可选参数的Groovy闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想定义一个带一个参数的闭包(用it
指代)
有时我想将另一个附加参数传递给闭包.
我怎样才能做到这一点?
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?
推荐答案
您可以将第二个参数设置为默认值(例如null):
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
另一种选择是使b
成为变量列表,如下所示:
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
这篇关于带可选参数的Groovy闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文