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:


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.


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

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:


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

This is the script:


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