我想定义一个函数,它接受另一个函数(闭包)作为参数。
第二个函数应该接受 1 个参数。
目前,我只有一个简单的签名:
def func1(func2) {
func2("string")
}
有没有办法明确指定,
func2
应该接受 1 个参数(或更少)?
最佳答案
不在 func1
的定义中,但是 you can check maximumNumberOfParameters
对于运行时的闭包,像这样:
def func1( func2 ) {
if( func2.maximumNumberOfParameters > 1 ) {
throw new IllegalArgumentException( 'Expected a closure that could take 1 parameter or less' )
}
func2( 'string' )
}
测试成功:
def f2 = { a -> "returned $a" }
assert func1( f2 ) == 'returned string'
和失败:
def f3 = { a, b -> "returned $a" }
try {
func1( f3 )
assert true == false // Shouldn't get here
}
catch( e ) {
assert e.message == 'Expected a closure that could take 1 parameter or less'
}
关于groovy - 如何定义一个接受参数化闭包作为参数的 Groovy 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11654129/