Skip to content
AgileLogics
5 min read

Groovy Truth and if Statements

Prerequisites: Operators

An if statement runs code only when a condition is true:

def temperature = 31

if (temperature > 30) {
    println 'Hot'
} else if (temperature > 15) {
    println 'Pleasant'
} else {
    println 'Cold'
}
Hot

The syntax is Java's: parentheses around the condition, braces around the body, else if for more branches.

Groovy Truth

In Java, a condition must be a boolean. Groovy accepts any value and decides whether it counts as true — the Groovy Truth:

def values = [true, false, 0, 1, -1, '', 'text', [], [0], [:], [a: 1], null]

values.each { v ->
    println "${v.inspect().padRight(8)} -> ${v ? 'true' : 'false'}"
}
true     -> true
false    -> false
0        -> false
1        -> true
-1       -> true
''       -> false
'text'   -> true
[]       -> false
[0]      -> true
[:]      -> false
['a':1]  -> true
null     -> false

These are falsy: false, null, 0, empty strings, empty collections and maps, and regex matchers with no match. Everything else is truthy. (inspect() prints a value the way you'd write it in code.)

Using it

def name = ''
def items = ['apple']

if (!name) println 'Please enter a name'
if (items) println "You have ${items.size()} item(s)"
Please enter a name
You have 1 item(s)

if (items) replaces Java's if (items != null && !items.isEmpty()). A one-statement body can skip the braces, but braces are safer when the body might grow.

The ternary operator

def score = 72
def result = score >= 50 ? 'pass' : 'fail'
println result
pass

Practice

Write a script that prints Fizz if a number is divisible by 3, Buzz if by 5, FizzBuzz if by both, and the number otherwise. Test it with 15, 9, 10, and 7.

Show solution
for (n in [15, 9, 10, 7]) {
    if (n % 15 == 0) {
        println 'FizzBuzz'
    } else if (n % 3 == 0) {
        println 'Fizz'
    } else if (n % 5 == 0) {
        println 'Buzz'
    } else {
        println n
    }
}
FizzBuzz
Fizz
Buzz
7