Lesson contents

Groovy — Organizing code across files

In Groovy, a package gives a helper class a qualified name. Once the class is compiled and on the classpath, another script can import and use it.

A simple example

Import a class

  1. Start with January 2, 2024
  2. Do this Import LocalDate, read the day
  3. Result 2
An import lets the script use the class by its short name.
Lesson.groovy
import java.time.LocalDate
println(LocalDate.of(2024, 1, 2).dayOfMonth)
Output
2
Advertisements

Share a function between source files

Compile the packaged helper to the current directory. The script imports the class, and its classpath includes the directory containing the compiled package.

Room capacity: 8 seats. Already booked: 3 seats. Helper returns: 5 free seats.
Share a room-capacity calculation

A club ticket desk has eight seats and three bookings. Keep the calculation in a helper file so both the booking screen and the check-in screen can use it. With the same inputs, each reports five places left.

Run the example

Groovy 4 on the JVM. Run these commands from the directory containing the example.

groovyc -d . boxes/BoxMath.groovy
groovy -cp . Lesson.groovy
boxes/BoxMath.groovy
package boxes

class BoxMath {
    static int remaining(int capacity, int used) {
        capacity - used
    }
}
Lesson.groovy
import boxes.BoxMath

println BoxMath.remaining(8, 3)
Output
5

Create the files with the names shown and run the command from their common project folder. The entry point gives the helper a capacity of 8 and a used count of 3. The helper returns 5.

Try it yourself

Change the used count from 3 to 8 in the caller.

Check your answer

Running the same command prints 0. No change to the helper is needed.

Groovy language documentation

Related tags

  • Groovy
  • modules
  • source files
  • imports