我想定义一个函数,它接受另一个函数(闭包)作为参数.第二个函数应该接受1个参数.
目前,我只有一个简单的签名:
def func1(func2) {
func2("string")
}
Run Code Online (Sandbox Code Playgroud)
有没有办法明确指定,func2应该接受1个参数(或更少)?
不是的定义func1,但你可以检查了maximumNumberOfParameters在运行时为关闭,就像这样:
def func1( func2 ) {
if( func2.maximumNumberOfParameters > 1 ) {
throw new IllegalArgumentException( 'Expected a closure that could take 1 parameter or less' )
}
func2( 'string' )
}
Run Code Online (Sandbox Code Playgroud)
测试成功:
def f2 = { a -> "returned $a" }
assert func1( f2 ) == 'returned string'
Run Code Online (Sandbox Code Playgroud)
失败:
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'
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30650 次 |
| 最近记录: |