In Groovy, it is possible to define methods inside a script (without being inside a class).
Example
src/ScriptMethodExample.groovyvoid printMultiples(int num, int times) {
for (int i = 1; i <= times; i++) {
print i * num + " "
}
}
printMultiples(3, 5) Output3 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.groovyint findFactorial(int num) {
num == 1 ? num : num * findFactorial(num - 1);
}
println findFactorial(6)
Output720
A method with void return type returns null:
src/VoidReturnValue.groovyvoid test() {
println "inside test method"
}
println test() Outputinside 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.groovyprintln "main script is returning value"
1+1 //returning value (we can also use keyword 'return')
Another script calling above one:
src/CallerScript.groovyprintln new MainScriptReturnsValue().run()
Output
main script is returning value
2
Example ProjectDependencies and Technologies Used: |