Skip to content
AgileLogics

Groovy Cheat Sheet

Learn Groovy from the basics →

Variables & Types

def name = 'Ada'
Untyped variable (any value)
int count = 3 / String s = 'x'
Typed variable (Java types)
final rate = 0.2 / val limit = 10
Constant (val is Groovy 6+)
def (a, b) = [1, 2]
Multiple assignment
3.14 / 3.14d / 42L / 42G
BigDecimal / double / long / BigInteger
'42' as int / '42'.toInteger()
Convert a string to a number

Strings

'plain' / "Hi $name, ${a + b}"
String / GString with interpolation
"""multi-line $x""" / '''multi-line'''
Triple-quoted strings
/\d+-\d+/
Slashy string: no escaping backslashes (regex)
s[0] / s[-1] / s[0..2]
Index and slice
s.tokenize(',') / list.join(', ')
Split (drops empties) / join
s.padLeft(5) / s.capitalize() / s * 3
Pad, capitalize, repeat

Operators

a == b / a.is(b) / a === b
Value equality / identity
user?.address?.city
Safe navigation (null instead of an exception)
name ?: 'default'
Elvis operator: default for falsy values
people*.name
Spread: collect a property from every item
a <=> b / x in list
Compare (-1, 0, 1) / membership
text ==~ /re/ / text =~ /re/
Full regex match / find

Control Flow

if (list) { ... }
Groovy Truth: empty/0/null are false
switch (x) { case 1..9 -> 'small'; default -> 'big' }
Switch expression (ranges, types, regex, closures)
for (x in items) { ... }
Loop over a collection or range
3.times { } / 1.upto(5) { } / 0.step(10, 2) { }
Counting loops with closures
try { ... } catch (IOException | IllegalStateException e) { ... }
Multi-catch (no checked exceptions)

Collections

def list = [1, 2, 3]; list << 4
ArrayList literal / append
def map = [name: 'Ada', age: 36]; map.name
LinkedHashMap literal / key access
[(key): value]
Use a variable as a map key
list.collect { it * 2 } / findAll { } / find { }
Map / filter / first match
list.inject(0) { acc, x -> acc + x }
Reduce
list.groupBy { } / countBy { } / collectEntries { [k, v] }
Group, count, build a map
list.sort(false) / list.toSorted()
Sorted copy (sort() mutates)

Methods & Closures

def greet(name, greeting = 'Hi') { "$greeting, $name" }
Method with default; last expression is returned
def sq = { x -> x * x } / { it * 2 }
Closure / implicit parameter it
list.each { println it }
Trailing closure, no parentheses
f.curry(1) / f >> g / f.memoize()
Curry, compose, cache
this.&greet / String::toUpperCase
Method pointer / method reference

Classes & Transforms

class P { String name }; new P(name: 'Ada')
Properties get getters/setters; named-arg constructor
@Canonical / @Immutable / @ToString
Generate equals, hashCode, toString, constructors
trait Greeter { String greet() { ... } }
Reusable behavior with state
record Point(int x, int y) {}
Immutable data class (Groovy 4+)
@CompileStatic / @TypeChecked
Static compilation / type checking

Data & Scripting

new JsonSlurper().parseText(text)
Parse JSON into maps and lists
JsonOutput.toJson(obj)
Generate JSON
new XmlSlurper().parseText(xml).book*.title
Navigate XML with GPath
new File('a.txt').text / file.eachLine { }
Read a file / stream lines
['git', 'status'].execute().text
Run a process and read its output
@Grab('group:artifact:version')
Pull a dependency into a script