Skip to content
AgileLogics
5 min read

How Groovy Code Runs

Prerequisites: Your first program

Groovy is compiled, even when it feels like a scripting language. When you run groovy hello.groovy:

  1. The Groovy compiler turns the file into JVM bytecode in memory. A script becomes a class (named after the file) whose run() method holds your top-level code. Syntax errors are reported now, before anything runs.
  2. The JVM loads and runs that class, just like compiled Java.
  3. In dynamic Groovy (the default), method and property lookups happen at runtime, so calling a method that doesn't exist is only reported when that line runs.

A syntax error

// illustrative — shows a compile error
println 'start'
println 'oops
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
C:\demo\main.groovy: 3: Unclosed string literal @ line 3, column 9.
   println 'oops
           ^

1 error

Nothing printed — not even "start" — because the file failed to compile. The message gives the file, the line, and the column. (Groovy 6 prints a timestamped SEVERE: log header above it, trimmed here.)

A runtime error

// illustrative — shows a runtime error
println 'start'
def name = 'Groovy'
println name.shout()
println 'never reached'
start
Caught: groovy.lang.MissingMethodException: No signature of method: shout for class: java.lang.String is applicable for argument types: () values: []
Possible solutions: split(), split(java.lang.String), split(groovy.lang.Closure), count(java.lang.CharSequence), split(java.lang.String, int), toShort()
	at main.run(main.groovy:4)

This time "start" printed, then the call failed with a MissingMethodException: strings have no shout() method. The compiler didn't complain, because in dynamic Groovy a method could be added at runtime (Level 3 shows how). The output was trimmed here: Groovy 6 also prints a log header line and dozens of Java stack frames. The line to look for is the one mentioning your file, main.groovy, and its line number.

Static compilation catches it earlier

// illustrative — shows a compile error
import groovy.transform.CompileStatic

@CompileStatic
void greet() {
    String name = 'Groovy'
    println name.shout()
}

greet()
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
C:\demo\main.groovy: 7: [Static type checking] - Cannot find matching method java.lang.String#shout(). Please check if the declared type is correct and if the method exists.
 @ line 7, column 13.
       println name.shout()
               ^

1 error

With @CompileStatic, the same mistake is a compile error. Level 2 covers static compilation in detail.

Compiling ahead of time

groovyc Hello.groovy writes .class files. They run on any JVM with the Groovy runtime jar on the classpath — that's how Groovy libraries and applications are shipped, usually built with Gradle.