Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking Groovy closures

If I define a closure in Groovy

def c = {println "foo"}

I can invoke it using either

c()

or

c.call()

AFAIK, these two are identical. However, I recently discovered a third way

c.doCall()

Are there any differences between call() and doCall()

Thanks, Don

like image 736
Dónal Avatar asked Jan 06 '10 17:01

Dónal


People also ask

How do I return a Groovy closure?

We can even return closures from methods or other closures. We can use the returned closure to execute the logic from the closure with the explicit call() method or the implicit syntax with just the closure object followed by opening and closing parentheses ( () ).

What package is the closure class located in Groovy?

Closure (Groovy 4.0. 4)

How do you call a method in Groovy?

In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.


1 Answers

The doCall method is what gets invoked when you call c() or c.call().

I found an example that claimed it's used to call the closure from inside itself, but that seems to work with call() too.

The documentation says you need to provide a doCall() method to specify the parameters in order to call the closure in the short form (without explicitly using call()). But I don't know how exactly they expect that to work.

Here's an explanation of call vs. doCall.

like image 88
Nathan Hughes Avatar answered Oct 25 '22 10:10

Nathan Hughes