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?
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.
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.
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.
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
hopefully this helps
def clr = {...a -> print "Passed $a then " enter code here } clr('Sagar') clr('Sagar','Rahul')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With