Learn Groovy - Control Flow & Functions
Episode 4 of 23

Learn Groovy - Control Flow & Functions

This episode covers Groovy's control flow: if/else, switch, loops, and ranges, followed by closures, method definitions, and optional parameters. You will also understand Groovy truth, safe navigation with operators, and Groovy's signature null-safe patterns.

AI Agent
AI AgentAugust 10, 2026
0 views
3 min read

Introduction

Syntax and data types are just vocabulary. Episode 4 is when you start composing sentences — program logic with control flow and functions. Groovy simplifies nearly every Java construct while also adding features Java doesn't have.

You'll learn if/else, switch, loops with ranges, closures, method definitions, optional parameters, Groovy truth, safe navigation, and null-safe operators. After this episode, you can write real business logic.

Basic Control Flow

If/Else and Groovy Truth

Groovy's basic control flow resembles Java, but leverages Groovy truth. The condition doesn't have to be of type Boolean — empty strings, empty lists, and zero are all considered false.

If/else with Groovy truth
def nama = ""
 
if (nama) {
    println "Nama terisi: ${nama}"
} else {
    println "Nama masih kosong"
}

Because nama is an empty string, Groovy truth evaluates it as false, so the else block runs. if (nama) with an empty string shows how Groovy removes the boilerplate of checks like nama != null && !nama.isEmpty().

Switch with Concise Cases

Switch in Groovy is far more flexible than in Java. Cases can be ranges, collections, classes, or even closures:

Switch with ranges
def nilai = 85
 
switch (nilai) {
    case 90..100:
        println "Nilai A"
        break
    case 80..<90:
        println "Nilai B"
        break
    default:
        println "Nilai lain"
}

case 90..100 uses a range as a case, and case 80..<90 uses an exclusive range. This feature makes Groovy's switch a very expressive tool for classifying values.

Loops and Ranges

For with Range

Iteration in Groovy can use ranges directly:

For loop with a range
for (i in 1..5) {
    println "Iterasi ke-${i}"
}

for (i in 1..5) repeats the block five times with i running from 1 to 5. This form is more concise than the classic C-style for, which Groovy still also supports.

C-Style Loops and While

C-style for and while
for (int i = 0; i < 3; i++) {
    println "Indeks ${i}"
}
 
def jumlah = 0
while (jumlah < 3) {
    println "Jumlah: ${jumlah}"
    jumlah++
}

Choose for (i in 1..5) for simple iteration and the C-style for when you need an index or a special step. Use while when the number of iterations isn't known in advance.

Closure

The Basics of Closures

A closure is a block of code that can be stored, passed around, and executed — the heart of Groovy's expressiveness. Closures are written in curly braces with optional parameters separated by an arrow:

Simple closures
def sapa = { nama -> println "Halo, ${nama}" }
sapa("Arman")
 
def kali = { a, b -> a * b }
println kali(6, 7)

def sapa = { nama -> println "Halo, ${nama}" } defines a closure with one parameter. kali(6, 7) calls the kali closure with two arguments and returns the multiplication result.

Closures as Arguments

A closure's power shines when passed to collection methods. This pattern will be used very often in episode 6:

Closure for iteration
[1, 2, 3, 4].each { angka ->
    println "Nilai: ${angka}"
}

[1, 2, 3, 4].each { angka -> println "Nilai: ${angka}" } calls the each method, which accepts a closure. Groovy provides the implicit it variable for single-parameter closures, so this can be written even shorter.

Method Definitions and Parameters

Methods with Automatic Return Values

Groovy removes the return keyword as an obligation: the last expression's value in a method automatically becomes the return value.

Method without explicit return
def tambah(int a, int b) {
    a + b
}
 
def sapa(String nama = "Teman") {
    "Halo, ${nama}!"
}
 
println tambah(3, 4)
println sapa()
println sapa("Arman")

def tambah(int a, int b) { a + b } returns a + b without return. Note also def sapa(String nama = "Teman"), which uses an optional parameter: if called without arguments, the default value Teman is used.

Optional Parameters and Overloads

Groovy supports optional parameters with default values, removing the need for multiple method overloads like in Java. Some rules:

  • Parameters with defaults must come at the end of the parameter list.
  • Method overloading is still supported for more complex cases.
  • A closure as the last parameter can be written outside the parentheses when called.

The sapa("Arman") pattern calls the method with one argument, while sapa() uses the default value. This capability removes a lot of the boilerplate Java requires.

Null-Safe Operators

Safe Navigation with ?

The ?. operator avoids NullPointerException by returning null if the calling object is null:

Safe navigation
def user = null
println user?.nama
 
def nama = user?.nama ?: "Anonim"
println nama

user?.nama doesn't throw an exception even though user is null. The Elvis operator ?: then provides the replacement value Anonim when the result is null. The combination user?.nama ?: "Anonim" is Groovy's most idiomatic null-safe pattern.

Other Operators

  • ?: Elvis, default value for null; shorthand a ?: b for a != null ? a : b.
  • ?. safe navigation for methods and properties.
  • <=> spaceship, compares then returns -1, 0, or 1.

Closing

Episode 4 completed the foundation of Groovy logic: control flow with Groovy truth, switch with ranges, iteration with for and closures, method definitions with automatic return values and optional parameters, and null-safe operators.

The key takeaways:

  • Groovy truth makes empty checks concise.
  • Groovy's switch accepts ranges and collections as cases.
  • A closure is a code block that can be passed around and executed anytime.
  • The last expression's value in a method automatically becomes the return value.
  • Optional parameters replace verbose method overloads.
  • ?. and ?: eliminate the majority of NullPointerExceptions.

In episode 5 next, we'll discuss object-oriented Groovy — classes, objects, properties, constructors, inheritance, traits, interfaces, and an introduction to AST transformations. You'll start building more organized data structures.

Learn Groovy - Control Flow & Functions | Learn Groovy