Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy. Is it possible to save a method into a var?

Tags:

groovy

Well, I want to save a method into a var to call it later. I want something like this:

class A {
     def sayHello() {
         "Hello"
     }
}

def a = new A()
def sayHelloMethod = a.sayHello
def result = sayHelloMethod()

Is there a way to do this?

like image 457
Rodrigo Villalba Zayas Avatar asked Jul 25 '16 01:07

Rodrigo Villalba Zayas


People also ask

How does Groovy handle method calls on Java objects?

Groovy does its magic by intercepting all method calls on objects (both Java objects and Groovy objects) and using its ExpandoMetaClass to add the behavior. However, it can't change how pure Java code determines which method to call on a pure Java class.

What can I do with non-type checked Groovy?

In normal, non type checked, Groovy, you can write things like: The method call works because of dynamic dispatch (the method is selected at runtime). The equivalent code in Java would require to cast o to a Greeter before calling the greeting method, because methods are selected at compile time:

How to return value from a method in Groovy?

The equivalent Java code of above Groovy example would be: A method in Groovy does not explicitly needs to use the return keyword to return a value. The last line having an expression is considered to be returned from the method. That applies to the methods declared in a class as well. A method with void return type returns null:

How to define variable types in Groovy?

For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser. There are following basic types of variable in Groovy as explained in the previous chapter −


2 Answers

I just found that the method pointer operator (.&) can be used to store a reference to a method in a variable.

class A {
   def sayHello() {
      "Hello"
   }
}

def a = new A()
def sayHelloMethod = a.&sayHello
assert a.sayHello() == sayHelloMethod()
like image 146
Rodrigo Villalba Zayas Avatar answered Nov 04 '22 04:11

Rodrigo Villalba Zayas


You can do:

class A {
     def sayHello() {
         "Hello"
     }
}

def a = new A()
def sayHelloClosure = { a.sayHello }
def result = sayHelloClosure.call()
like image 44
Strelok Avatar answered Nov 04 '22 03:11

Strelok