Skip to content
If/Else and Switch
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow

Standard if/else if/else. Groovy's switch is far more powerful than Java's — it matches by value, type, range, regex, or closure:

switch (x) {
    case 0:           println "zero"; break
    case 1..10:       println "small"; break
    case Integer:     println "some int"; break
    case ~/[a-z]+/:   println "lowercase word"; break
    case { it > 100 }: println "big"; break
    default:          println "other"
}

No more wrapping integers in Integer. No more enum boilerplate. The closure case { it > 100 } is the killer.

Truthiness in Groovy:

  • null is false
  • 0, 0.0 are false
  • empty string, empty list, empty map are false
  • everything else is true

So:

if (list) { ... }       // true if list is non-empty
if (str) { ... }        // true if str is non-empty

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…