Switch Expression

Groovy has always had much more powerful switch statements compared to Java. Class case values, regular expression case values, collection case values, closure case values, or at the end, equal values case. All these options made the switch statement a first-class citizen in the Groovy world. And now, following the latest updates in the Java programming language, Groovy also supports a switch expression. The main difference between a switch statement and a switch expression is that the latter introduces a syntax compatible with Java and returns a value. You can still use a variety of combinations as cases, but the new syntax will make your code a bit more elegant. 



switch (value) {
case null -> ‘just a null’
case 0 -> ‘zero’
case 1 -> ‘one’
case { it instanceof List && it.empty } -> ‘an empty list’
case List -> ‘a list’
case ‘007’ -> ‘James Bond’
case ~/d+/ -> ‘a number’
default -> ‘unknown’


Records, a handy immutable “data carrier” type, were introduced in Java 16. Now, they are also available in Groovy. The same syntax, though Groovy also introduces a `@RecordType` annotation that you can use interchangeably. And even if this is not that a game-changer as it was for Java, it’s good to see Groovy heading up with the latest features introduced in its mother language.

Generated by Feedzy