Is there a way to pass a method as a parameter in Groovy without wrapping it in a closure? It seems to work with functions, but not methods. For instance, given the following:
def foo(Closure c) { c(arg1: "baz", arg2:"qux") } def bar(Map args) { println('arg1: ' + args['arg1']) println('arg2: ' + args['arg2']) }
This works:
foo(bar)
But if bar
is a method in a class:
class Quux { def foo(Closure c) { c(arg1: "baz", arg2:"qux") } def bar(Map args) { println('arg1: ' + args['arg1']) println('arg2: ' + args['arg2']) } def quuux() { foo(bar) } } new Quux().quuux()
It fails with No such property: bar for class: Quux.
If I change the method to wrap bar
in a closure, it works, but seems unnecessarily verbose:
def quuux() { foo({ args -> bar(args) }) }
Is there a cleaner way?
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.
It is used to separate where you declare bindings for your closure from the actual code, eg: def myClosure = { x, y -> x + y } the part before -> declares that the closure has two arguments named x and y while the second part is the code of the closure.
If you want to call this method in Groovy you can do it by passing a list cast to String[] , e.g. Ex 1: Adding column Jan... Adding column Feb... Adding column Mar... Adding column Apr... Ex 2: Adding column Jan... Adding column Feb... Adding column Mar... Adding column Apr... I hope it helps.
The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language. Here, firstName will be a String, and listOfCountries will be an ArrayList. Here, multiply can return any type of object, depending on the parameters we pass to it.
.&
operator to the rescue!
class Quux { def foo(Closure c) { c(arg1: "baz", arg2:"qux") } def bar(Map args) { println('arg1: ' + args['arg1']) println('arg2: ' + args['arg2']) } def quuux() { foo(this.&bar) } } new Quux().quuux() // arg1: baz // arg2: qux
In general, obj.&method
will return a bound method, i.e. a closure that calls method
on obj
.
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