Close

Groovy Operators - Method Pointer Operator

[Last Updated: Dec 6, 2018]

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

def power = Math.&pow
def result = power(2, 4)
println result

Output

16.0

Instance method pointer

src/Example2InstanceMethodPointer.groovy

def bd = BigDecimal.valueOf(2)
def pow = bd.&pow
def result = pow(4)
println result

Output

16

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

void doSomething(def param) {
    println "In doSomething method, param: " + param
}

def m = this.&doSomething
m("test param");

Output

In 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.groovy

class Task {
    void run(def param) {
        println "task running param: " + param;
    }
}

def task = new Task();
def run = task.&run
run("test param");

Output

task running param: test param

Passing method pointer to a method

src/Example5PassingToMethod.groovy

void printResults(List list, def param, def method){
    for (def e : list){
       println method(e, param);
    }
}

printResults([1,3,5,6], 3, Math.&pow)

Output

1.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.groovy

void doSomething(int i){
       println "integer $i"
}
void doSomething(String s){
    println "String $s"
}

def m = this.&doSomething
m(4)
m("hi")

Output

integer 4
String hi

Type of the method pointer

src/Example7TypeOfMethodPointer.groovy

def m = Math.&floor;
println m.getClass()

Output

class 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 Project

Dependencies and Technologies Used:

  • Groovy 2.5.3
  • JDK 9.0.1
Groovy - Method pointer operator Select All Download
  • groovy-method-pointer-operator
    • src
      • Example1StaticMethodPointer.groovy

    See Also