Groovy Cheat Sheet
Practical Groovy syntax covering closures, collections, GDK operators, and classes for the JVM dynamic language.
Basics
Variables, strings, and optional typing.
// Variables and string interpolationdef name = "World"println "Hello, ${name}!"int x = 42String s = "Value: $x"// Optional typingdef add(a, b) { a + b }println add(2, 3)
Closures
Groovy's first-class blocks of code.
def square = { x -> x * x }println square(5)def greet = { String n -> "Hi, $n" }println greet("Groovy")[1, 2, 3].each { println it } // 'it' = implicit single paramdef doubled = [1, 2, 3].collect { it * 2 }
Collections
Lists, maps, and functional-style methods.
- [1, 2, 3]- List literal
- [a: 1, b: 2]- Map literal
- list.each { }- Iterate over elements
- list.collect { }- Transform each element, like map()
- list.findAll { it > 1 }- Filter elements matching a condition
- list.inject(0) { acc, v -> acc + v }- Reduce/fold with an accumulator
Language Features
Groovy-specific operators and idioms.
- def- Declares a dynamically-typed variable
- ?.- Safe navigation operator, avoids NullPointerException
- ?:- Elvis operator, provides a default when the left side is falsy/null
- ==- Calls .equals() (structural equality), unlike Java's ==
- GString- Double-quoted string supporting ${} interpolation
- @groovy.transform.Immutable- Annotation that generates an immutable class
Classes
Defining a class with a map-based constructor.
class Person { String name int age String greet() { "Hi, I'm ${name}, ${age} years old" }}def p = new Person(name: "Ada", age: 30) // named-arg constructorprintln p.greet()
GString Interpolation
Embed expressions and multiline text in strings.
def name = 'Ada'def greeting = "Hello, ${name}!" // GStringdef calc = "Sum: ${1 + 2 + 3}" // any expressiondef lazy = "Now: ${-> new Date()}" // lazy closure evaldef block = """ Multi-line ${name} spans rows"""def raw = 'No $interpolation here' // single quotes = plain String
MarkupBuilder & JsonBuilder
Generate structured output with Groovy builders.
import groovy.xml.MarkupBuilderdef writer = new StringWriter()new MarkupBuilder(writer).html { head { title 'Page' } body { p 'Hello' }}import groovy.json.JsonBuilderdef json = new JsonBuilder()json.person { name 'Ada'; age 36 }println json.toPrettyString()
Operator Overloading
Define operators by implementing named methods.
class Vector { int x, y Vector plus(Vector o) { new Vector(x: x + o.x, y: y + o.y) } Vector multiply(int s) { new Vector(x: x * s, y: y * s) } String toString() { "($x, $y)" }}def a = new Vector(x: 1, y: 2)def b = new Vector(x: 3, y: 4)assert (a + b).toString() == '(4, 6)' // calls plus()assert (a * 2).toString() == '(2, 4)' // calls multiply()
Groovy Operators
Convenience operators unique to Groovy.
- ?.- safe navigation: returns null instead of NPE (obj?.field)
- ?:- Elvis operator: name ?: 'default' when left is falsy
- *.- spread-dot: apply to every element (list*.name)
- <=>- spaceship: comparison returning -1/0/1
- ==~- match: true if string fully matches a regex
- =~- find: creates a Matcher for a regex
- as- coercion: '42' as Integer, list as Set
- .&- method reference: this.&methodName
Traits
Reusable, stateful behavior mixed into classes.
trait Greetable { String name String greet() { "Hi, I'm ${name}" }}trait Auditable { void log(String msg) { println "[audit] $msg" }}class User implements Greetable, Auditable {}def u = new User(name: 'Ada')assert u.greet() == "Hi, I'm Ada"u.log('created')
Use the Elvis operator (value ?: default) instead of a verbose ternary null-check — it's idiomatic Groovy and reads far more cleanly.