switch
statements in Groovy are infinitely more flexible, powerful and applicable than in Java. For this reason I've just found myself wanting to use a nested switch
for the first time in Groovy.
With this:
outerSwitch:
switch( var1 ){
case 'x':
...
break
case 'y':
switch( var2 ){
case 'a':
// something
break outerSwitch
...
}
...
}
... I get a horrid message from the Groovy compiler saying "Groovy: the break statement with named label is only allowed inside loops". I don't know whether this is the same with Java.
There is an obvious silly workaround: you enclose your outer switch
with a while( true )
, apply the outerSwitch
label to that, and put a break
statement at the end of your outer switch
.
Or you could do a for( int i = 0; i < 1; i++ )
... or use a Groovy-er idiom for the same thing, I forget what all the options are... although having tried
outerSwitch:
1.times{
switch( var1 ){
...
}
... I find that the Groovy compiler gives the same nasty message. So you can't fool it with a closure, seemingly.
Is there anything in the Groovy toolkits and boxes of tricks which lets you jump out of the outer switch
from the nested switch
more sensibly?
The trouble being, I suppose, that when you break
from a case
block you don't do so with a value... if you could go break true
or break 'fiddle-de-dee'
there'd be obvious ways to solve this.
An obvious workaround is that you can precede your nested switch
with def breakouter = false
and then change that as applicable in the case
block. I'd just hope that Groovy would provide something more elegant...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…