我想定义一个带有一个参数的闭包(我用it
引用)
有时我想将另一个参数传递给闭包。
我怎样才能做到这一点?
答案 0 :(得分:36)
您可以将第二个参数设置为默认值(例如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
像这样的vararg List:
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
答案 1 :(得分:1)
希望这有助于
def clr = {...a ->
print "Passed $a then "
enter code here
}
clr('Sagar')
clr('Sagar','Rahul')
答案 2 :(得分:0)
@tim_yates 中的变体不适用于 @TypeChecked
(在类上下文中),至少在Groovy 2.4.11
处有效默认arg被忽略,无法编译: - (
所以在这种情况下可行的其他(公认的丑陋)解决方案是:
首先声明关闭似乎工作正常(无论如何都需要递归):
def cl
cl = { ... }
@TypeChecked(value=TypeCheckingMode.SKIP)
它会对两者都有效,但是你会松开对方法(或类,取决于你把它放在哪里)的类型检查
声明关闭代理cl2
:
@TypeChecked
class Foo {
static main( String[] args ) {
def cl = { a, b ->
if( b != null )
print "Passed $b then "
println "Called with $a"
}
def cl2 = { a -> cl( a, null ) }
cl2( 'Tim' ) // prints 'Called with Tim'
cl( 'Tim', 'Yates' ) // prints 'Passed Yates then Called with Tim
}
}
将闭包转换为类方法,例如
@TypeChecked
class Foo {
cl( a, b=null ) {
if( b != null )
print "Passed $b then "
println "Called with $a"
}
static main( String[] args ) {
cl( 'Tim' ) // prints 'Called with Tim'
cl( 'Tim', 'Yates' ) // prints 'Passed Yates then Called with Tim
}
}