Groovy Reference
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. The reference material consulted while preparing these pages is listed in the section bibliography. |
Welcome to the Groovy reference. Apache Groovy is a dynamic, optionally typed language for the
Java platform. It compiles to JVM bytecode, calls any Java library directly, and adds concise syntax on top of Java:
closures, string interpolation, collection and map literals, properties, operators that map to methods, builders and
domain specific languages. The same source can be a one-line script, a build file, a test, or a statically compiled
library. Groovy’s standard library extensions, the Groovy Development Kit (GDK), add hundreds of methods to JDK classes
such as String, File, List and Map, which is where much of its day-to-day productivity comes from.
History
Groovy was started by James Strachan in 2003 and developed at Codehaus, with a first 1.0 release in January 2007 and a
specification request, JSR 241, that has been dormant since 2012. Pivotal (earlier SpringSource and VMware) sponsored
its development until March 2015; Groovy then entered the Apache Incubator in March 2015 and graduated to an Apache
top-level project in November 2015. Along the way the language gained annotations and
generics (1.5), AST transformations and Grape (1.6), static type checking and compilation and extension modules
(2.0), traits (2.3), the Parrot parser with lambdas and var (3.0), the org.apache.groovy coordinates, records,
sealed types and GINQ (4.0), JDK 11 and the new groovysh (5.0), and native async/await, val, module imports and
many new modules (6.0). Every release is listed with its date in
What’s New and Migrating from Older Versions.
Release baseline
This section documents Apache Groovy 6.0 (6.0.0, released 2026-09-22; JDK 17 or newer), checked on 2026-10-14. Features that are newer than Groovy 4.0 are marked with the release that introduced them, and features that the official documentation labels incubating are labelled as such. On the check date the maintained lines were 6.0.0 (2026-09-22), 5.1.3 (2026-09-19), 5.0.8 (2026-07-29), 4.0.33 (2026-07-29) and 3.0.25 (2025-05-24, the last release of the 3.0 line). Frameworks and tools built on Groovy, such as Gradle, Grails, Spock, Geb, Micronaut and Jenkins pipelines, are not documented here; they are listed with a brief description and links on Ecosystem & Groovy in Other Tools, and Spock and Geb get a single page only because the official Groovy testing guide covers them.
The greenhouse scenario
The examples share one small, original domain: a greenhouse toolkit that monitors and waters a hobby greenhouse. It
suits Groovy’s strengths — scripting, data processing, DSLs and Java interoperability — and grows page by page: a
Plant class with properties, a Reading record, a sealed Zone hierarchy with Bench, HangingBasket and Bed,
traits for watering and alerting, a small watering DSL, sensor logs in CSV, plant data in JSON, a seed catalogue in XML,
TOML and YAML configuration, an in-memory H2 database queried with groovy.sql.Sql and GINQ, a report rendered with a
template engine, asynchronous sensor polling and tests. A page whose concept fits the scenario poorly uses a minimal
standalone example instead. Every example on these pages was run with Groovy 6.0.0 on JDK 26, and the output shown is
the real output of that run (examples that use third-party tools and were not run are labelled as such on their page).
How the book was used
A copy of the first edition of Groovy in Action (Dierk König with Andrew Glover, Paul King, Guillaume Laforge and Jon
Skeet, Manning Publications, 2007), which describes Groovy 1.0, was consulted as a reference for concept coverage and
structure. It is not the source of any example: every example is written against the current official Groovy 6.0
documentation, the official documentation wins wherever the two differ, and no text, code listing or figure is copied
from the book. Its core-language and classic-library chapters are still conceptually sound; its chapters on tooling,
GroovyTestCase, Scriptom, early Grails and XML-RPC or SOAP are outdated or out of scope. Each page states in prose where
older material is outdated for the concepts it touches, and
What’s New and Migrating from Older Versions
collects the legacy-to-modern replacements. The book’s second edition (Manning, 2015, Groovy 2.4) is the current
edition; it was not used as a source.
New here? Read in this order
-
Getting Started — install Groovy and run a first script.
-
Differences with Java — what changes if you know Java.
-
Running Scripts & the groovy Command — run scripts and one-liners.
-
Strings & GStrings — string literals and interpolation.
-
Lists & Arrays — list literals and indexing.
-
Maps — map literals and access.
-
Operators: Arithmetic, Relational & Logical — the everyday operators.
-
Control Structures —
if,switch, loops and their Groovy extras. -
Classes, Fields & Properties — classes and properties.
-
Closures — the heart of everyday Groovy.
-
Closure Delegation: Owner, Delegate & This — how closures resolve names.
-
Working with Collections — the GDK collection methods.
-
Traits — reusable behaviour.
-
Static Type Checking & @CompileStatic — compile-time checking and static compilation.
-
JSON — parsing and building JSON.
-
XML Parsing, GPath & Security — reading XML.
-
Runtime Metaprogramming & the MOP — the meta-object protocol.
-
AST Transformations: Code Generation & Class Design — compile-time code generation.
-
Domain Specific Languages — building DSLs.
-
Testing with JUnit & groovy-test — testing Groovy code.
The other pages can be read in any order as you need them. Coming from an older book or tutorial? Start with What’s New and Migrating from Older Versions.
What’s covered
Getting started
-
Getting Started — what Groovy is and where it came from, installing it (SDKMAN!, Homebrew, zip, Docker, Windows), JDK requirements per release line, Maven and Gradle coordinates and a first script.
-
Differences with Java — every documented difference from Java with a side-by-side example, from default imports and multi-methods to
==and primitives. -
Groovy & Other Languages — everyday idioms mapped from Java, Kotlin, Scala, Python and Ruby, and the trade-offs of dynamic typing.
-
Running Scripts & the groovy Command — the
groovycommand,-e,-n,-p,-i, the shebang line, arguments, exit codes and the classpath rules. -
groovysh & groovyconsole — the JLine 3 REPL and the Swing console, their commands, history and embedding.
Syntax and fundamentals
-
Lexical Structure, Comments, Keywords & Identifiers — comments, the shebang, reserved and contextual keywords, normal and quoted identifiers.
-
Strings & GStrings — the six literal forms, escapes, interpolation, lazy GStrings and the GString versus String pitfalls.
-
Numbers & Numeric Literals — literal forms,
BigDecimalby default, suffixes, result types of arithmetic and promotion. -
Booleans & the Groovy Truth — how every type is coerced to a boolean and how to customise it with
asBoolean(). -
Lists & Arrays — list literals, indexing, slicing, operators, arrays and primitive arrays.
-
Maps — map literals, key rules, access styles,
withDefault, spread maps and the common methods. -
Ranges — inclusive and exclusive ranges, stepping, ranges of characters and dates, and custom
Comparableranges. -
Variables, Typing, def, var & val —
def, explicit types,var,val,final, multiple assignment and destructuring. -
Program Structure, Packages, Imports & Scripts — packages, default and aliased imports, module imports, and scripts versus classes.
Operators
-
Operators: Arithmetic, Relational & Logical — arithmetic, relational, logical, bitwise, ternary and Elvis operators with the precedence table.
-
Object Operators — safe navigation, direct field access, method pointers and references, spread, spaceship and subscript operators.
-
Regular Expressions — the pattern, find and match operators, groups, slashy strings and the GDK regex helpers.
-
Operator Overloading — the operator-to-method table, comparison rules and compound-assignment overloading.
Control structures and semantics
-
Control Structures —
if,switchwithisCase, switch expressions, loops, labels and the position rule. -
Exceptions & Error Handling —
try/catch/finally, multi-catch, try-with-resources and the dynamic exceptions. -
Assertions & Power Assert —
assert, power-assert output and assertions as executable documentation. -
Type Coercion & Promotion — casts versus
as, number promotion, closure to SAM coercion and map and list coercion. -
Optionality — what may be left out: parentheses, semicolons,
returnandpublic.
Object orientation
-
Classes, Fields & Properties — classes, inner classes, fields versus properties, accessors and visibility.
-
Methods, Constructors & Parameters — methods, named-argument constructors, default and named parameters, varargs.
-
Inheritance, Interfaces & Generics — inheritance, abstract classes, interfaces with default methods, duck typing and generics.
-
Traits — trait methods, state, composition, conflicts and runtime traits.
-
Records & Sealed Types — records, compact constructors,
copyWithand sealed hierarchies. -
Enums & Annotations — enums with bodies, defining and using annotations.
Closures and functional programming
-
Closures — closure syntax, parameters, captured variables, coercion and closures versus lambdas.
-
Closure Delegation: Owner, Delegate & This — how a closure resolves names:
this, owner, delegate, resolve strategies and@DelegatesTo. -
Functional Programming — currying, memoization, composition, trampolines and
java.util.functioninterop.
Typing
-
Static Type Checking & @CompileStatic —
@TypeChecked,@CompileStatic, flow typing and closure parameter hints. -
Type Checking Extensions — writing extensions to the static type checker with the event API.
-
Built-in Type Checkers — the checkers shipped in
groovy.typecheckers, fromRegexCheckertoNullChecker.
The GDK
-
GDK Overview & Object Methods — how the GDK extends the JDK, the
Objectmethods,ConfigSlurper,Expandoand observable collections. -
Working with Collections — iterating, filtering, transforming, aggregating, sorting and combining collections.
-
Files I/O & Paths — reading, writing and traversing files and
Pathobjects. -
External Processes — running commands with
execute(), process streams, pipes and timeouts. -
Dates & Times —
java.timeextensions, formatting, parsing and theTimeCategoryduration DSL.
Metaprogramming
-
Runtime Metaprogramming & the MOP — the Meta-Object Protocol,
invokeMethod,methodMissing,propertyMissingand interception. -
Metaclasses, ExpandoMetaClass & Categories — metaclasses,
ExpandoMetaClassanduse(Category). -
Extension Modules — writing, packaging and using instance and static extension methods.
-
AST Transformations: Code Generation & Class Design —
@ToString,@Canonical,@Builder,@Delegate,@Lazyand the other class-design transformations. -
AST Transformations: Logging, Safety, Concurrency & Directives — logging, concurrency, cloning, safety and directive transformations.
-
Writing AST Transformations & Macros — compilation phases, local and global transformations, the AST API and macros.
Concurrency
-
Async/Await — native
async/awaitandAwaitablein Groovy 6.0 (incubating). -
Generators, Channels & Structured Concurrency — generators, channels, selects and structured concurrency scopes (incubating).
-
Parallel Collections & Dataflow — parallel collection methods, pools and dataflow variables in
groovy.concurrent. -
Actors, Agents & Active Objects —
Agent,Actorand@ActiveObjectmessage-passing concurrency.
Data and module guides
-
JSON —
JsonSlurper,JsonOutput,JsonBuilderand typed parsing. -
XML Parsing, GPath & Security —
XmlParser,XmlSlurper, GPath and secure-by-default parsing. -
XML: Creating & Manipulating —
MarkupBuilder,StreamingMarkupBuilderand editing XML trees. -
YAML & TOML —
YamlSlurper,TomlSlurper, builders and typed parsing. -
CSV & Markdown —
CsvSlurper,CsvBuilderandMarkdownSlurper(incubating). -
Databases with Groovy SQL —
groovy.sql.Sql, queries, transactions, batches and datasets. -
GINQ: SQL-like Collection Queries — GINQ queries with
from,where, joins, grouping and windows. -
Template Engines — the
groovy.textengines, fromSimpleTemplateEnginetoMarkupTemplateEngine. -
HTTP Client with HttpBuilder — the
HttpBuilderclosure DSL over the JDKHttpClient(incubating). -
Builders — the builder pattern, the built-in builders and writing your own.
DSLs and scripting
-
Domain Specific Languages — command chains, script base classes,
@DelegatesToand type-checked DSLs. -
Compilation Customizers & Secure Scripting —
CompilerConfiguration, customizers and running untrusted scripts safely.
Integration and tools
-
Integrating Groovy into Java Applications —
GroovyShell,GroovyClassLoader,GroovyScriptEngineand JSR 223. -
Compiling with groovyc & Joint Compilation —
groovyc, its options and joint compilation with Java. -
Build Tools: Gradle, Maven & Ant — building Groovy with Gradle, Maven (GMavenPlus) and Ant.
-
Grape Dependency Management —
@Grab, thegrapecommand and its resolvers. -
GroovyDoc — doc comments, Markdown comments, the
groovydoctool and its build integrations. -
Groovlets, Servlets & JMX — Groovlets, servlet integration and JMX management.
-
Performance, invokedynamic & Native Images — invokedynamic call sites, static compilation and GraalVM native images.
Testing
-
Testing with JUnit & Groovy Test — JUnit 4, 5 and 6,
GroovyAssert, mocks and test annotations. -
Testing with Spock & Geb — Spock specifications and Geb browser tests (third-party).
-
Design by Contract with groovy-contracts —
@Requires,@Ensures,@Invariantand the contract annotations.
Practice and reference
-
Style Guide & Idioms — the official style guide rules with before-and-after examples.
-
Design Patterns in Groovy — the 21 classic patterns expressed in idiomatic Groovy.
-
What’s New & Migrating from Older Versions — every release from 1.0 to 6.0, legacy-to-modern table and migration notes.
-
Ecosystem & Groovy in Other Tools — projects built on or embedding Groovy, each with a brief description and links.
-
Cheat Sheet (PDF) — a one-page, printable summary of the whole section, with a legacy-to-modern strip.
Bibliography
The reference material consulted while preparing this section. The official Apache Groovy documentation is the primary
source for every page; the book is a consulted reference for concept coverage only, and the third-party projects are
cited only on the ecosystem and testing pages. On any discrepancy, the official documentation wins. No text, code
listing or figure is copied from any book or documentation page. Each page lists the subset it derives from under its
own == References heading.
Official Apache Groovy documentation
-
Groovy documentation index and the Groovy Language Documentation (single page), also available as a PDF; the project site is groovy.apache.org and the language site groovy-lang.org.
-
Language and semantics: Syntax, Program structure, Operators, Semantics, Differences with Java, Object orientation, Closures, Object orientation (single page) and Semantics (single page).
-
Metaprogramming, DSLs and typing: Metaprogramming, Domain specific languages, groovy-contracts, invokedynamic support.
-
The GDK and libraries: Groovy Development Kit, GDK overview, the GDK reference, the API reference (Javadoc) and the GAPI API reference (GroovyDoc), Databases, Template engines, GINQ, HttpBuilder, JSON, XML, YAML, TOML, CSV, Markdown, async/await, Concurrency with Java, Parallel collections, Dataflow and Actors.
-
Tools and integration: groovy, groovyc, groovysh, groovyConsole, GroovyDoc, Grape and Grape (single page), Integrating Groovy, Build tools: Gradle, Servlets, JMX, Testing, Design patterns, IDEs and Ecosystem.
-
Style guide, Security, Versioning, Learn (books and tutorials).
-
Download and installation: Download, Download (groovy-lang.org), Install and the Groovy Docker image.
-
Release notes: Releases, Change logs, and the release notes for 1.5, 1.6, 1.7, 1.8, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 3.0, 4.0, 5.0, 5.1 and 6.0.
-
Groovy Enhancement Proposals, cited where a page uses one: the GEP index, GEP-13 (sealed types), GEP-15 (compound assignment operator overloading), GEP-16 (
valtype placeholder for final declarations), GEP-20 (multi-assignment destructuring), GEP-21 (broadening AST transform awareness under joint compilation), GEP-22 (traits) and GEP-27 (compact closure and lambda compilation). -
The Apache Groovy blog, only for posts a page cites, for example Using Groovy with Apache Wayang.
-
Source code: apache/groovy.
Specifications and standards
-
JSR 241 (The Groovy Programming Language, dormant), JSR 223 (Scripting for the Java Platform), JSR 310 (Date and Time API) and JSR 305 (Annotations for Software Defect Detection).
-
The JDK Enhancement Proposals Groovy aligns with: JEP 213, JEP 371, JEP 394 (
instanceofpatterns), JEP 400, JEP 411 (Security Manager deprecation), JEP 413 ({@snippet}), JEP 445 and JEP 512 (instance main methods), JEP 444 (virtual threads), JEP 467 (Markdown doc comments), JEP 476 and JEP 511 (module imports). -
Java platform documentation: the Java Language Specification, SE 21 (chapter 5 and chapter 15), Virtual threads, javax.script, HttpClient, HttpServer, Pattern and JMX.
-
Data formats: RFC 4180 (CSV), RFC 3986 (URIs), CommonMark, RFC 8259 (JSON), XML 1.0, YAML 1.2 and TOML 1.0.
-
Numbers: IEEE 754-2019 (Standard for Floating-Point Arithmetic).
Book
-
Dierk König, with Andrew Glover, Paul King, Guillaume Laforge and Jon Skeet, Groovy in Action, Manning Publications, 2007. ISBN 1-932394-84-2 (978-1-932394-84-9). Written for Groovy 1.0; consulted for concept coverage only. The current edition is the second edition (Manning, 2015, Groovy 2.4), which was not used as a source.
Third-party projects (cited only on the ecosystem, testing and tools pages; none is documented further)
-
Testing: Spock (2.5 documentation), Geb (now hosted by Apache Groovy; formerly https://gebish.org/), JUnit and Apache JMeter.
-
Build and automation: Gradle (Groovy plugin), Apache Ant, GMavenPlus, Jenkins Pipeline and SDKMAN!.
-
Frameworks and data: Apache Grails, Micronaut, Ratpack (archived), Spring Framework, Nextflow, Apache Wayang, JasperReports and H2.
-
Tools and libraries: IntelliJ IDEA, Groovy-Eclipse, Visual Studio Code, Apache NetBeans, Groovy Web Console, CodeNarc, GPars, Griffon and BeakerX.