带有可选参数的 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屋!
查看全文