Rodrigo Villalba Zayas
Rodrigo Villalba Zayas

Reputation: 5636

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

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?

Upvotes: 6

Views: 1896

Answers (2)

Rodrigo Villalba Zayas
Rodrigo Villalba Zayas

Reputation: 5636

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()

Upvotes: 9

Strelok
Strelok

Reputation: 51461

You can do:

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

def a = new A()
def sayHelloClosure = { a.sayHello }
def result = sayHelloClosure.call()

Upvotes: 1

Related Questions