Groovy — Switch statements and grouped cases
A Groovy switch can match several kinds of case values. A collection case tests membership and can route several strings through one branch.
A simple example
Match one case
- Start with Value 2
- Do this Match case 2
- Result two
switch (2) {
case 2: println("two"); break
default: println("other")
}
two
Route several event states to one action
Map queued and retry to the same pending action. A sent event is complete, and an unrecognized state is sent for review. The list case accepts either pending state. Returning from each branch exits the method immediately, and default supplies a fallback.
A parcel dashboard receives status updates. A queued parcel and a parcel awaiting retry both belong in the pending tray. Mark a sent parcel done and send unfamiliar statuses for review.
Run the example
Use Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
String route(String state) {
switch (state) {
case ['queued', 'retry']: return 'pending'
case 'sent': return 'done'
default: return 'review'
}
}
['queued', 'retry', 'sent', 'unknown'].each { println route(it) }
pending pending done review
Both pending states share one result. The other branches distinguish a known completion from a new or misspelled status.
Try it yourself
What should an unrecognized state such as paused produce?
Check your answer
It produces review. Add an explicit case when the application defines how to handle that state.