Code reuse is an important part of programming. The smallest possible way is to create functions and call them several times in the same code. The next step is to have a set of functions in a file and use those functions in several other files.

In this example we see how to do that with simple functions.

Importing function

In this example we have a very simple "library" file with a simple function:

examples/groovy/function_tools.gvy

def greet() {
    println "Hello World!"
}

Next to it there is another file in which we load the former file into memory and then call it.

examples/groovy/function_script.gvy

GroovyShell shell = new GroovyShell()
def tools = shell.parse(new File('function_tools.gvy'))
tools.greet()

We can then run

groovy function_script.gvy

In the code we gave the path to the library so in this version it needs to be next to the code loading it.

Importing class methods

This is the class:

examples/groovy/class_tools.gvy

class Tools {
    def greet() {
        println "Hello World!"
    }
}

This is the script:

examples/groovy/class_script.gvy

def tools = new GroovyScriptEngine( '.' ).with {
    loadScriptByName( 'class_tools.gvy' )
}
this.metaClass.mixin tools
greet()