Control Flow and Groovy Truth

Site Admin · 11 Sep 2026 · 8 views

Standard Control Flow

Groovy supports all of Java's control flow statements but often with simplified syntax. The key difference is how Groovy evaluates truthiness.

if/else and Ternary

def age = 25

// Groovy allows parentheses to be optional
if (age >= 18) {
    println "Adult"
} else {
    println "Minor"
}

// Ternary operator
def status = age >= 18 ? "Adult" : "Minor"

// Elvis operator (null-safe ternary)
def name = "Alice"
println name ?: "Unknown"  // Alice
def nullName = null
println nullName ?: "Unknown"  // Unknown

Groovy Truth

Groovy evaluates objects as boolean values using "Groovy Truth" rules:

  • false, null, 0, empty strings, and empty collections are falsy
  • Non-null objects, non-zero numbers, and non-empty collections are truthy
def list = []
if (list) {
    println "Has items"
} else {
    println "Empty"  // This prints
}

println "text" ? true : false   // true
println "" ? true : false        // false
println 0 ? true : false         // false

Switch Statements

Groovy's switch is more powerful than Java's, supporting multiple types in a single case:

def value = 42
switch (value) {
    case "string": println "String"; break
    case 42: println "The answer"; break
    case 1..10: println "Between 1 and 10"; break
    case [1, 2, 3]: println "One, two, or three"; break
    default: println "Other"
}

Safe Navigation

The ?. operator safely navigates through null references:

def user = null
println user?.name  // null instead of NullPointerException

Key Points

  • Groovy Truth treats empty collections, empty strings, null, and 0 as false.
  • The Elvis operator ?: provides concise null fallbacks.
  • Safe navigation ?. prevents NullPointerExceptions.
  • Switch statements support type matching and ranges.
  • Parentheses around conditions are optional.
Share this post:

Comments (0)

Please login or register to comment.