我想定义一个带有一个参数的闭包(我用it
引用这个参数),有时我想向闭包传递另一个额外的参数。我该怎么做呢?
发布于 2012-09-25 09:54:31
您可以将第二个参数设置为默认值(如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
发布于 2016-05-19 06:58:06
希望这能帮助
def clr = {...a ->
print "Passed $a then "
enter code here
}
clr('Sagar')
clr('Sagar','Rahul')
发布于 2018-04-06 08:25:57
的变体不能与@TypeChecked
(在类上下文中)一起工作,至少在Groovy 2.4.11
中不能工作,在Groovy 2.4.11
中,默认参数被忽略,并且不编译 :-(
因此,在这种情况下可以工作的其他(诚然更丑陋的)解决方案是:
closure first似乎工作得很好(对于递归来说无论如何都是必要的):
def cl ={ ... }
- at least in Eclipse Neon / Groovy-Eclipse Plugin 2.9.2 the code completion/suggestions do not work either way using the closure later on in the same code block => so nothing lost as far as I can say
带有@TypeChecked(value=TypeCheckingMode.SKIP)
的
cl2
:@TypeChecked class Foo { static main( String[] args ){ def cl ={ a,b -> if( b != null ) print“传递了$b然后”println“用$a调用”} def cl2 ={a -> cl( a,null )} cl2( 'Tim‘) //打印’用Tim‘cl( 'Tim',' Yates‘) //打印’传递的Yates然后用Tim调用}}
@TypeChecked class Foo { cl( a,b=null ){ if( b != null ) print“通过$b然后”println“用$a调用”} static main( String[] args ){ cl( ' Tim‘) //用Tim’cl( 'Tim',' Yates‘) //打印’通过Yates然后用Tim调用} }
https://stackoverflow.com/questions/12580262
复制相似问题