// control.groovy — if, switch, loops and "Groovy truth". // Groovy truth: these all count as false in a condition def falsy = [null, 0, '', [], [:], false] falsy.each { value -> assert !value } println 'null, 0, empty string, empty list, empty map and false are all "false"' def customer = '' if (!customer) { println 'No customer given' // runs: empty string is false } // Elvis operator: value if it's "true", otherwise a default def name = customer ?: 'Guest' println name // Guest // switch is very flexible in Groovy def describe(value) { switch (value) { case null -> 'nothing' case Integer -> "a number: $value" case ~/[A-Z]{2}-\d{3}/ -> "a SKU: $value" case ['NEW', 'OPEN'] -> 'an open status' case { it instanceof List && it.size() > 2 } -> 'a long list' default -> "something else: $value" } } ['AX-200', 42, 'NEW', [1, 2, 3], null, 'hello'].each { println describe(it) } // Loops for (sku in ['AX-200', 'BX-310']) println "for-in: $sku" 3.times { i -> println "times: $i" } 1.upto(3) { println "upto: $it" } def n = 0 while (n < 2) { println "while: ${n++}" }