How to define a Groovy function which accepts parametrized closure as a parameter?
groovy
Solution
Not in the definition of `func1`, but you can check the `maximumNumberOfParameters` for a Closure at runtime, like so:
def func1( func2 ) {
if( func2.maximumNumberOfParameters > 1 ) {
throw new IllegalArgumentException( 'Expected a closure that could take 1 parameter or less' )
}
func2( 'string' )
}
Testing success:
def f2 = { a -> "returned $a" }
assert func1( f2 ) == 'returned string'
And failure:
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'
}
Problem
I want to define a function, which accepts another function (closure) as a parameter. The second function should accept 1 parameter. Currently, I have just a simple signature: ``` def func1(func2) { func2("string") } ``` Is there a way to explicitly specify, that `func2` should accept 1 parameter (or less)?