I have the following switch statement
switch (points) {
case 0: name = "new"; break;
case 1..14: badgeName = "bronze-coin"; break;
case 15..29: badgeName = "silver-coin"; break;
default: badgeName = "ruby";
}
I'd like the first case (case 0) to include points less than or equal to 0. How can I do this in Groovy?
The switch case statement is the comparison between a variable and its possible values. Break statement is used to come out of the switch block immediately without any further comparisons. Default statement is executed only when there is no case with value same as the variable value.
A switch statement can replace multiple if checks. It gives a more descriptive way to compare a value with multiple variants.
You can use a JavaScript switch greater than the expression same as using in an if-else statement.
switch(points)
{
case Integer.MIN_VALUE..0: badgeName = "new"; break;
case 1..14: badgeName = "bronze-coin"; break;
case 15..29: badgeName = "silver-coin"; break;
default: badgeName = "ruby";
}
case { it instanceof Integer && it < 0 }:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With