Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Less than in Groovy case/switch statement

Tags:

groovy

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?

like image 901
RyanLynch Avatar asked May 05 '10 05:05

RyanLynch


People also ask

Can I compare in switch case?

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.

Which type of values switch () statement compares?

A switch statement can replace multiple if checks. It gives a more descriptive way to compare a value with multiple variants.

Can we use greater than in switch case?

You can use a JavaScript switch greater than the expression same as using in an if-else statement.


2 Answers

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";
}
like image 122
J. Skeen Avatar answered Oct 12 '22 04:10

J. Skeen


case { it instanceof Integer && it < 0 }:
like image 20
RyanLynch Avatar answered Oct 12 '22 05:10

RyanLynch