Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a Groovy function which accepts parametrized closure as a parameter?

Tags:

groovy

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)?

like image 416
Roman Avatar asked Feb 19 '23 18:02

Roman


1 Answers

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'
}
like image 130
tim_yates Avatar answered Mar 22 '23 22:03

tim_yates