Friday, December 25, 2009

Groovy - Different ways to invoke closure or method with closure as parameter

Closure is one of the most powerful features of Groovy. In Groovy, if a method takes closure as a parameter, there are several different ways to invoke the method. Also, there are different ways to invoke a closure. I'll also show some cases which you might expect to work, but don't. These can sometimes be confusing for a beginner. I'll show them with examples here.

Invoking method with closure as parameter:

The below method takes closure as it's second parameter.

def getOddNumbers(n, closure) {
for (int i=1; i<=n; i+=2) {
println "in method ${closure(i)}"

There are many ways (i.e syntaxes) to invoke this method:

1) getOddNumbers(10, {
println it

The closure is the second parameter passed to method. All it does is print the number and return that number. Now, we'll see the other ways.

2) getOddNumbers 10, {
println it

This syntax is same as 1, except that the open and close braces are optional. This really has nothing to do with closure, but I wanted to show this other syntax also.

3) getOddNumbers(10) {
println it

If closure is the last parameter to the method, then it can be passed as a separate code block like above. This is very elegant and widely used way to pass closure to a method.

4) printingClosure = {
println it
getOddNumbers(10, printingClosure)

We can assign closure to variable and use that in our method call later. Also,
getOddNumbers 10, printingClosure will work too i.e we can omit braces here. But getOddNumbers(10) printingClosure does not work though.

Invoking Closure:

Also, there are different ways to invoke the closure. In our above method, we used closure(i) to invoke the closure. We could also do closure i to invoke the method. This works as long as we don't use the return value. But, if we do
x = closure i or println closure i, this fails. closure(i) works fine in these cases and is the common way to invoke closure.


malini ecorp said...

) provides GROOVY in hyderabad with best faculties on real time projects. We give the best online trainingamong the GROOVY in Hyderabad. Classroom Training in Hyderabad India

best seo said...

This is an amazing post for me as well as for all.Well anyways thanks for the post and keep on sharing.for more info

bharat u said...

excellent blog good information provides.
Seo Online Training and Services in Vizag, Vijayawada,Hyderabad
Most of the students got placed immediately after the SEO training at SaiSantosh

Click here:
seo training in hyderabad

Rohit P said...

That was really helpful information on codes
Thanks author

make this page to viewed by more students or people who are in need get seo done for this page, seo training shall help to gain knowledge on how to do it seo training in bangalore