Match “fallthrough”: executing same piece of code for more than one case?

前端 未结 4 900
死守一世寂寞
死守一世寂寞 2020-12-17 07:38

What is the Scala\'s way to write the following code:

 int i;

 switch(i) {
   case 1:  
         a();
         break;

   case 2:
   case 15:
        b();
          


        
4条回答
  •  一个人的身影
    2020-12-17 08:25

    Case statements can actually include additional logic guards using a standard if statement. So you could do something like:

    i match {
      case x if x == 1 => a
      case x if (x == 2 | x == 15) => b; c;
      case _ => foo
    }
    

    The matching guards can be any boolean function or composition of functions, so it gives it a lot more power than the standard switch statement in Java.

提交回复
热议问题