Groovy Goodness: Using The Switch Expression
Groovy supports more classifiers for a switch
case
statement than Java. Since Groovy 4 we can use switch
also as an expression. This means the switch
statement returns a value without having to use return
. Instead of using a colon (:
) and break
we use the →
notation for a case
. We specify the value that the switch
expressions returns after →
. When we need a code block we simply put the code between curly braces ({…}
).
In the following example we use the switch
expression with different case
statements:
def testSwitch(val) {
switch (val) {
case 52 -> 'Number value match'
case "Groovy 4" -> 'String value match'
case ~/^Switch.*Groovy$/ -> 'Pattern match'
case BigInteger -> 'Class isInstance'
case 60..90 -> 'Range contains'
case [21, 'test', 9.12] -> 'List contains'
case 42.056 -> 'Object equals'
case { it instanceof Integer && it < 50 } -> 'Closure boolean'
case [groovy: 'Rocks!', version: '1.7.6'] -> "Map contains key '$val'"
default -> 'Default'
}
}
assert testSwitch(52) == 'Number value match'
assert testSwitch("Groovy 4") == 'String value match'
assert testSwitch("Switch to Groovy") == 'Pattern match'
assert testSwitch(42G) == 'Class isInstance'
assert testSwitch(70) == 'Range contains'
assert testSwitch('test') == 'List contains'
assert testSwitch(42.056) == 'Object equals'
assert testSwitch(20) == 'Closure boolean'
assert testSwitch('groovy') == "Map contains key 'groovy'"
assert testSwitch('default') == 'Default'
Written with Groovy 4.0.3.