Groovy: import and use functions from another file

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 these examples we see how to do that with simple functions and methods of classes.

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'))
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:

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

This is the script:

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

Importing class methods

import tools

t = new tools()
t.hello()            // Hello World

// this also works:
new tools().hello()  // Hello World

class tools {
    def hello() {
        println("Hello World")
    }
}

Import class from a subdirectory

import tools.other
new other().hi()
package tools

class other {
   def hi() {
       println("Hello Again")
   }
}

Import static methods from a class

This is probably the version most similar to importing individual functions.

import static tools.hello as hi
hi()

class tools {
    static hello() {
        println("Hello World")
    }
}

Import static methods from a class from a subdirectory

import static some.other.Tools.hello as hi
hi()

package some.other

class Tools {
    static hello() {
        println("Hello World")
    }
}


timestamp: 2018-09-13T20:30:01 tags:

  • GroovyShell