Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Language Basics

Control Flow and Groovy Truth

Learn Groovy conditions and loops: Groovy truth rules, if/else, ternary, the powerful switch with classifiers, for-in, while, break/continue, and iteration with each and times.

Control flow in Groovy looks like Java, with two big upgrades. First, Groovy truth: almost any value can be used as a condition, so if (name) replaces if (name != null && !name.isEmpty()). Second, the switch statement accepts much more than constants: ranges, lists, classes, regular expressions and closures. This lesson covers conditions, loops and the extra tools Groovy gives you for both.

Groovy examples are read-only here; Java stand-ins are runnable.

Groovy truth

When a value appears in a condition, Groovy converts it to a boolean using these rules:

Value Truth
null false
0, 0.0 false
Non-zero number true
Empty string '' false
Non-empty string true
Empty collection or map false
Non-empty collection or map true
Empty Optional, Iterator with no next, Matcher with no match false
Any other object true (unless it defines asBoolean())
A Boolean its own value
GROOVY
def items = []
if (items) { println 'has items' } else { println 'no items' }    // no items

def name = 'Ada'
if (name) { println "hello $name" }                               // hello Ada

assert !'' && !null && !0 && ![:] && !0.0
assert 'false' as boolean       // careful: the string 'false' is non-empty, so true

Notice the last line: a non-empty string is true even if its text says "false". Convert text yourself with Boolean.parseBoolean(text).

You can add truth to your own classes by defining asBoolean():

GROOVY
class Basket {
    List items = []
    boolean asBoolean() { !items.isEmpty() }
}
assert !new Basket()

The stand-in below spells out the rules in Java, which is the work Groovy does behind the scenes.

Java Java stand-in: Groovy truth as a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

if, else and the ternary

GROOVY
def score = 82
if (score >= 90) {
    println 'A'
} else if (score >= 80) {
    println 'B'
} else {
    println 'C'
}

def label = score >= 50 ? 'pass' : 'fail'
def display = name ?: 'unknown'      // Elvis shortcut

Braces are optional for one-statement branches but recommended. Groovy's if is a statement, not an expression, so you cannot write def x = if (...) 1 else 2. Use the ternary operator.

switch

Groovy's switch tests each case with isCase, which is far more flexible than Java's ==:

GROOVY
def describe(x) {
    switch (x) {
        case 0:               return 'zero'
        case 1..9:            return 'a digit'
        case [10, 20, 30]:    return 'round number'
        case Integer:         return 'some other integer'
        case ~/\d+/:          return 'digits in a string'
        case String:          return 'a string'
        case { it instanceof List && it.size() > 2 }: return 'a long list'
        case null:            return 'null'
        default:              return 'something else'
    }
}

println describe(5)       // a digit
println describe(20)      // round number
println describe(99)      // some other integer
println describe('123')   // digits in a string
println describe('hey')   // a string
println describe(null)    // null

Cases are checked in order and the first that matches wins. Like Java, a case falls through to the next unless you break or return. Cases can be constants, ranges, lists (membership), classes (instance of), patterns (regex match) and closures (truthy result).

Groovy 4 also supports the newer switch expression with arrows:

GROOVY
def size = switch (n) {
    case 0 -> 'empty'
    case 1..3 -> 'small'
    default -> 'large'
}

The Java stand-in below uses a pattern-matching switch with the same intent, to show how classification-style dispatch looks in modern Java.

Java Java stand-in: classifying values with switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Loops

for

GROOVY
for (int i = 0; i < 3; i++) { print i }         // 012 (classic)
for (i in 0..<3) { print i }                    // 012 (range, end excluded)
for (item in ['a', 'b']) { print item }         // ab
for (entry in [x: 1, y: 2]) { print "$entry.key=$entry.value " }
for (char c in 'hey') { print c }               // hey

for (x in collection) works on lists, ranges, maps, strings, arrays and anything iterable.

while and do/while

GROOVY
def n = 3
while (n > 0) { print n--; }      // 321

do { ... } while (cond) also works in Groovy 3+.

break and continue

break leaves a loop and continue skips to the next iteration, as in Java. Inside a closure (such as the body of each), they are not available: return only ends the current closure call (acting like continue). To stop early use a normal loop or methods such as find, any and takeWhile from Collection Methods in Depth.

Iteration methods

Groovy numbers and collections have methods that replace loops:

GROOVY
3.times { println "round $it" }
1.upto(3) { println it }
['a', 'b'].eachWithIndex { v, i -> println "$i: $v" }

try, catch, finally

GROOVY
try {
    Integer.parseInt('x1')
} catch (NumberFormatException e) {
    println "bad number: ${e.message}"
} finally {
    println 'done'
}

You can list several exception types with catch (IOException | IllegalStateException e). Groovy does not force you to catch checked exceptions.

Early exits and guard clauses

Because the last expression is the return value, short methods often use guard clauses:

GROOVY
def sign(n) {
    if (n == 0) return 'zero'
    n > 0 ? 'positive' : 'negative'
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these values is false in a Groovy condition?

    An empty collection is false. The string 'false' is non-empty (true), [0] has an element (true), and -1 is non-zero (true).
  2. 2. Which case label would match the value 7 in a Groovy switch?

    A range case tests membership with isCase, so 7 is in 1..9.
  3. 3. What does return do inside the closure of list.each { ... }?

    A closure's return ends that single invocation. To stop an each early, use a regular for loop or find/any.
  4. 4. How do you write a range loop that counts 0, 1, 2?

    0..<3 excludes the end. 0..3 would include 3.

Summary

  • Groovy truth makes null, 0, empty strings and empty collections false, and nearly everything else true.
  • switch accepts constants, ranges, lists, classes, regexes and closures.
  • for (x in ...), while, times, upto and eachWithIndex cover looping.
  • break and continue do not work inside closures; use find, any or a real loop.
  • Exceptions follow Java, but checked exceptions are optional to catch.

Next: Lists