Change Groovy switch statement
If a Groovy 3 switch statement has a default branch, it must be the last branch. This means that you can no longer place the default branch in any other position except last in the list of branches.
The following does not compile under Groovy 3:
switch(yourVariable) {
default:
// default action
break
case 'a':
// case a action
break
}
To correct the above code, place the default branch last:
switch(yourVariable) {
case 'a':
// case a action
break
default:
// default action
break
}
Your code will behave exactly the same as all the branches have a break
statement, so each branch is isolated and doesn’t affect other branches.
Switch fall-through
As switch fall-through occurs when branches don't have a break
statement, making it possible to execute multiple branches, not only the one that matches.
Example of switch fall-through:
def result = ""
switch(yourVariable) {
default:
result += "default "
// as there is no break statement, "case a" will be executed next
case 'a':
result += "a "
// as there is no break statement, "case b" will be executed next
case 'b':
result += "b"
}
When yourVariable
has the value 'a', the result
variable will equal "a b". When yourVariable
has the value 'b', the result
variable will equal "b". In all other cases, the result
variable will be equal “default a b”.
To make the code compile under Groovy 3, place the default branch last. However, to obtain the same results as the fall-through switch, you must also adjust the rest of the code:
Groovy 3 switch fall-through equivalent:
def result = ""
switch(yourVariable) {
case 'a':
result = "a b"
break
case 'b':
result = "b"
break
default:
result = "default a b"
break
}