a groovy switch case statement with several variables

Viewed 7716

Is it possible to have a switch-case statement with more than a variable in groovy? I tried with tuples but the case part doesn't accept more than one argument.

I am trying to avoid several nested if statements so instead of

if (a==1) {
  if (b==2) {
    if (c==3) {
      // do something
    }
  }
}
else {
  if (a==4) {
    if (b==5) {
      if (c==6) {
        //do something else 
      }
    }
  }
}

Can I do:

switch(a,b,c) { 
  case : (1,2,3) // if a==1, b==2 and c==3
    // do something 
    ... 
  case : (4,5,6)
    // do something else  
    ... 
  } 
}
3 Answers

Based on your edit, I believe that this should work:

if (a == 1 && b == 2 && c == 3) {
  // do something
} else if (a == 4 && b == 5 && c == 6) {
  // do something else
}

If you want a switch statement instead, that's possible:

def val = [a, b, c]
switch (val) {
    case {it == [1, 2, 3]}:
        // something
        break;
    case {it == [4, 5, 6]}:
        // something else
        break;

Groovy is just dirty java, you don't need any class definition. everything you write in a java method you can write it directly in groovy.

switch (num) {
case 1:
case 2:
case 3:
   System.out.println("1 through 3");
   break;
case 6:
case 7:
case 8:
    System.out.println("6 through 8");
 break;
}

To answer your question, inside the switch we need an expression, not function parameters.

class Solution{
 static void main (String...args){
BufferedReader br=new BufferedReader(new 
InputStreamReader(System.in))
def val=br.readLine()        
     switch(val){
       case('E0'):
         println "Basic"
         break;
         default:
         break;
         case('E1'):
         println "Inter"
         break;
         case('E2'):
         println "Advance"
         break;
       default:
       println "not defined"
       
              }
          
  }
}
Related