带有多个变量的常规开关案例语句

时间:2019-01-16 16:30:25

标签: groovy switch-statement

在Groovy中是否可能有一个switch-case语句包含多个变量?我尝试使用元组,但案例部分接受的参数不止一个。

我正在尝试避免使用多个嵌套的if语句,而不是

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

我可以这样做:

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  
    ... 
  } 
}

2 个答案:

答案 0 :(得分:1)

Groovy只是肮脏的Java,您不需要任何类定义。用Java方法编写的所有内容都可以直接用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;
}

要回答您的问题,在开关内部,我们需要一个表达式,而不是函数参数。

答案 1 :(得分:1)

根据您的修改,我认为这应该可行:

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

如果您确实确实希望使用switch语句,则可以:

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

但是我不确定为什么您会比if / else块更喜欢它。