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
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 ( () ).
Closure (Groovy 4.0. 4)
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.
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.
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