The Groovy Language
[ 76 ]
The switch statement
Groovy adds some neat features to the switch statement by adding some extra
options that can be tested in the case expression:
switch (x) {
case 1:
// if x is number 1 we end up here
break;
case "mymatch":
// if x equals string "mymatch" we end up here
break;
case /.o./:
// if x is a string and matches regex /.o./ we end up here
break;
case ["apple", "orange","pear", 1, 2, 3]:
// if x is found in the list we end up here
break;
case [a: 1, b: 2]:
// If x is a key of the map we end up here
break;
case 1..5:
// if x is one of the values 1, 2, 3, 4 or 5 we end up here
break;
}
Loops
Groovy does not support the traditional Java do { } while (condition) style of
looping. This does support traditional while loops, as follows:
int n = 0;
while ( n++ < 10) {
println n
}
Groovy makes up for this lack of looping options with its own style of looping.
Groovy loops are simpler and in many ways more powerful than the Java
equivalent. In Groovy, we can iterate over any range of values, as follows:
for ( n in 0..10)
println n
http://www.ebook3000.com