Skip to content

Groovy Cheatsheet

Agile dynamic language for the JVM with Java-like syntax and powerful features.

01

Getting Started

Hello World

Groovy is Java-compatible but more concise.

groovy
println "Hello, World!"

Variables

def for dynamic typing, explicit types also work.

groovy
def x = 10
def s = "hello"
int y = 20

Closures

Closures are code blocks; 'it' is the default parameter.

groovy
def square = { n -> n * n }
println square(5)

[1, 2, 3].each { println it }

Strings

Double quotes allow ${} interpolation, single quotes do not.

groovy
def name = "World"
println "Hello, ${name}!"
println 'No interpolation'
02

Data Structures

Lists

<< adds to list; collect is map.

groovy
def lst = [1, 2, 3]
lst << 4
lst.each { println it }
lst.collect { it * 2 }

Maps

Maps use [:] literal; .property access.

groovy
def m = [a: 1, b: 2]
m.c = 3
println m.a
m.each { k, v -> println "$k=$v" }

Ranges

Ranges are first-class objects.

groovy
def r = 1..5
r.each { println it }
(1..10).findAll { it % 2 == 0 }
03

Advanced

Classes

Classes similar to Java but with less boilerplate.

groovy
class Person {
    String name
    int age
}

def p = new Person(name: "Alice", age: 30)
println p.name

GStrings

GStrings support arbitrary expressions in ${}.

groovy
def items = [1, 2, 3]
println "Items: ${items.join(", ")}"
println "Sum: ${items.sum()}"

Was this helpful?