Groovy basics: what the language is and where it is used
What Groovy is
Groovy is an object-oriented programming
language for the Java platform. It compiles to bytecode, the same
instructions a Java compiler produces, so a
Groovy class is an ordinary JVM class and Java libraries need no
adapter.
James Strachan wrote the first version in 2003, and version 1.0 appeared
in 2007. The language went through the Java Community Process as
JSR-241.
The syntax is Java-like, and the ceremony is optional: a type can be
def, a statement needs no semicolon, strings
interpolate with ${}, and collections have literal
syntax. Closures, builders and operator overloading arrived long before
the Java language had them. The typing is dynamic by default, and
@CompileStatic puts the compiler back in charge
when speed or a type check matters.
Where Groovy is used
Gradle build scripts are Groovy, and countless projects run them without
knowing the language. Tests written with Spock are Groovy, the Grails
framework builds web applications with it, and
Jenkins pipelines are Groovy scripts in a
Jenkinsfile.
The other side is scripting: an application embeds Groovy to let a user
extend it, as SoapUI does with its test
scripts and iReport with report expressions. The language is a bridge
between the strictness of Java and the brevity of a script.
Install Groovy
Groovy needs a JDK, so install Java first and check it:
java -version
openjdk version "21.0.5" 2024-10-15
On Ubuntu and Debian the distribution package is enough to try the language:
sudo apt install -y groovy
groovy -v
Groovy Version: 4.0.24 JVM: 21.0.5 Vendor: Eclipse Adoptium OS: Linux
The package of the distribution is often older than the current release. SDKMAN and the archive on groovy.apache.org install a newer one side by side, and a project that uses Gradle downloads its own copy.
Hello, Groovy
Save one line as hello.groovy. A script needs no class and no main method:
println "Hello, Groovy"
groovy hello.groovy
Hello, Groovy
The Java form works too, and shows that the two languages share a structure:
class Hello {
static void main(String[] args) {
println "Hello, Groovy"
}
}
A file with a class compiles ahead of time with groovyc, which writes the same .class files as javac, and the JVM runs them with the Groovy runtime on the classpath.
Where to go next
The first error a beginner meets is a missing JDK or a version mismatch
between the JDK and the Groovy release; the
Groovy errors page collects the
messages and their causes.
The same JVM also runs Java and Kotlin, and a
Gradle build mixes the two languages without a second toolchain.
Version numbers move with every release: a newer Groovy prints its own version, and the Hello, Groovy line is the same on all of them.
Article author: Arthur Isaev