Reputation: 5636
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
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
Reputation: 51461
You can do:
class A {
def sayHello() {
"Hello"
}
}
def a = new A()
def sayHelloClosure = { a.sayHello }
def result = sayHelloClosure.call()
Upvotes: 1