The method pointer operator (.&) can be used to store a reference to a method in a variable.
Let's see quick examples to understand Groovy method pointer.
Static method pointer
src/Example1StaticMethodPointer.groovydef power = Math.&pow
def result = power(2, 4)
println result
Output16.0
Instance method pointer
src/Example2InstanceMethodPointer.groovydef bd = BigDecimal.valueOf(2)
def pow = bd.&pow
def result = pow(4)
println result
Output16
Script method pointer
We can get instance of the current script object with this and then we can use this.&myMethod to get the method pointer:
src/Example3LocalMethodPointer.groovyvoid doSomething(def param) {
println "In doSomething method, param: " + param
}
def m = this.&doSomething
m("test param");
OutputIn doSomething method, param: test param
class method pointer
This is similar to the first two examples. In this example we are going to create our own class:
src/Example4ClassMethod.groovyclass Task {
void run(def param) {
println "task running param: " + param;
}
}
def task = new Task();
def run = task.&run
run("test param");
Outputtask running param: test param
Passing method pointer to a method
src/Example5PassingToMethod.groovyvoid printResults(List list, def param, def method){
for (def e : list){
println method(e, param);
}
}
printResults([1,3,5,6], 3, Math.&pow)
Output1.0 27.0 125.0 216.0
Overloaded methods resolution
For overloaded methods the resolution is done during runtime depending on the type of parameters:
src/Example6OverloadedMethods.groovyvoid doSomething(int i){
println "integer $i"
}
void doSomething(String s){
println "String $s"
}
def m = this.&doSomething
m(4)
m("hi")
Outputinteger 4 String hi
Type of the method pointer
src/Example7TypeOfMethodPointer.groovydef m = Math.&floor;
println m.getClass()
Outputclass org.codehaus.groovy.runtime.MethodClosure
The type of method pointer is an implementation of groovy.lang.Closure , so that means the method pointer can be used at any place a closure is used. We will cover Groovy closures in an upcoming tutorial.
Example ProjectDependencies and Technologies Used: |