Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Closure with optional arguments

Tags:

I want to define a closure which takes one argument (which i refer to with it ) sometimes i want to pass another additional argument to the closure. how can i do this?

like image 985
Moonlit Avatar asked Sep 25 '12 09:09

Moonlit


People also ask

How do I use lambda expression in Groovy?

The Groovy syntax doesn't support the lambda expressions, but we can rely on closure coersion to use Groovy closures as Java lambda expressions in our code. In the following sample we use the Java Streams API. Instead of lambda expressions for the filter and map methods we use Groovy closures.

What is the role of closure and listeners in Groovy?

It references the variables which are declared in its surrounding scope. We know that anonymous inner classes are not supported by Groovy. Inline listeners can be determined with the help of closures. In groovy, listener closures are used as listener adapters.

How do I return a value in Groovy?

The last line of a method in Groovy is automatically considered as the return statement. For this reason, an explicit return statement can be left out. To return a value that is not on the last line, the return statement has to be declared explicitly.


2 Answers

You could set the second argument to a default value (such as 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 

Another option would be to make b a vararg List like so:

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 
like image 134
tim_yates Avatar answered Sep 28 '22 00:09

tim_yates


hopefully this helps

​def clr = {...a ->       print "Passed $a then "     enter code here  }  ​clr('Sagar') clr('Sagar','Rahul') 
like image 35
Sagar Mal Shankhala Avatar answered Sep 28 '22 00:09

Sagar Mal Shankhala