Close

Groovy - Methods In Scripts

[Updated: Nov 8, 2018, Created: Nov 7, 2018]

In Groovy, it is possible to define methods inside a script (without being inside a class).

Example

src/ScriptMethodExample.groovy

void printMultiples(int num, int times) {
    for (int i = 1; i <= times; i++) {
        print i * num + " "
    }
}

printMultiples(3, 5)

Output

3 6 9 12 15 

The generated class has all user defined methods. The code outside of the methods is copied into the run method.

Let's compile above file with groovyc and analyze the compiled class with javap.

D:\groovy-script-methods\src>groovyc ScriptMethodExample.groovy
D:\groovy-script-methods\src>javap ScriptMethodExample
Compiled from "ScriptMethodExample.groovy"
public class ScriptMethodExample extends groovy.lang.Script {
public static transient boolean __$stMC;
public ScriptMethodExample();
public ScriptMethodExample(groovy.lang.Binding);
public static void main(java.lang.String...);
public java.lang.Object run();
public void printMultiples(int, int);
protected groovy.lang.MetaClass $getStaticMetaClass();
}

The equivalent Java code of above Groovy example would be:

import groovy.lang.Script;
import org.codehaus.groovy.runtime.InvokerHelper;

public class ScriptMethodExample extends Script {
 
    public void printMultiples(int num, int times) {
        for (int i = 1; i <= times; i++) {
            System.out.print(i * num + " ");
        }
    }

    public Object run() {
        printMultiples(3, 5);
        return null;
    }

    public static void main(String[] args) {
        InvokerHelper.runScript(ScriptMethodExample.class, args);
    }
}

Return keyword is optional

A method in Groovy does not explicitly needs to use the return keyword to return a value. The last line having an expression is considered to be returned from the method. That applies to the methods declared in a class as well.

Example

src/OptionalReturnExample.groovy

int findFactorial(int num) {
    num == 1 ? num : num * findFactorial(num - 1);
}

println findFactorial(6)

Output

720

A method with void return type returns null:

src/VoidReturnValue.groovy

void test() {
    println "inside test method"
}

println test()

Output

inside test method
null

Main script returning result

As seen in above Java equivalent code the run method also returns a value which can be captured in another script.

Example

src/MainScriptReturnsValue.groovy

println "main script is returning value"
1+1 //returning value (we can also use keyword 'return')

Another script calling above one:

src/CallerScript.groovy

println new MainScriptReturnsValue().run()

Output

main script is returning value
2

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.3
  • JDK 11
Groovy - Using methods in Scripts Select All Download
  • groovy-script-methods
    • src
      • ScriptMethodExample.groovy

    See Also