Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass method as parameter in Groovy

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?

like image 359
David Moles Avatar asked Mar 05 '13 18:03

David Moles


People also ask

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.

What is -> in 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.

How do I pass a string in Groovy?

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.

How do I define a function in Groovy?

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.


1 Answers

.& 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.

like image 143
epidemian Avatar answered Oct 05 '22 01:10

epidemian