Close

Groovy Operators - Call Operator

[Last Updated: Aug 11, 2020]

If a class A has a method call() then it can be called directly on A's instance. i.e.

class A{
  def call(){
   ...
  }
}
def a = new A()
a()

In above example a() is equivalent to a.call()

Example

class SumParser {
    private String input;

    SumParser(String input) {
        this.input = input
    }

    int call() {
        int sum = 0;
        for (String s : input.split("\\+")) {
            sum += Integer.parseInt(s)
        }
        return sum;
    }
}

def sumParser = new SumParser("1+3+7")
def result = sumParser()
println result;
println "explicitly using call()"
def result2 = sumParser.call()
println result2;

Output

11
explicitly using call()
11

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.6
  • JDK 9.0.1
Groovy call operator example Select All Download
  • groovy-call-operator
    • src
      • Example1Call.groovy

    See Also