Skip to content
AgileLogics
5 min read

The switch Statement

Prerequisites: Groovy Truth and if statements

Groovy's switch is far more flexible than Java's classic one. A case can match a value, a type, a range, a list, a regular expression, or a closure:

def describe(value) {
    switch (value) {
        case null:          return 'nothing'
        case 0:             return 'zero'
        case 1..9:          return 'a small number'
        case Integer:       return 'a big integer'
        case ~/\d+-\d+/:    return 'looks like a code'
        case ['red', 'green', 'blue']: return 'a primary color'
        case String:        return 'some text'
        case { it instanceof List && it.size() > 2 }: return 'a long list'
        default:            return 'something else'
    }
}

[null, 0, 7, 500, '12-34', 'green', 'hello', [1, 2, 3], 2.5].each {
    println "${it.inspect()}: ${describe(it)}"
}
null: nothing
0: zero
7: a small number
500: a big integer
'12-34': looks like a code
'green': a primary color
'hello': some text
[1, 2, 3]: a long list
2.5: something else

Cases are tried from top to bottom and the first match wins, so put specific cases before general ones (1..9 before Integer). Behind the scenes Groovy calls isCase on each case value — ranges check containment, classes check instanceof, closures are called.

Fall-through and break

With the classic colon syntax, execution continues into the next case unless you break (or return):

def day = 'Sat'
switch (day) {
    case 'Sat':
    case 'Sun':
        println 'Weekend'
        break
    default:
        println 'Weekday'
}
Weekend

Switch expressions

Since Groovy 4, the arrow form produces a value and never falls through:

def grade(int score) {
    switch (score) {
        case 90..100 -> 'A'
        case 80..<90 -> 'B'
        case 70..<80 -> 'C'
        default -> 'F'
    }
}

println grade(95)
println grade(84)
println grade(42)

def size = switch ('M') {
    case 'S', 'M' -> 'regular'
    case 'L' -> 'large'
    default -> 'unknown'
}
println size
A
B
F
regular

Prefer the arrow form for new code: it's shorter, and forgetting a break is impossible.