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

前端 未结 4 898
死守一世寂寞
死守一世寂寞 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:13

    According to this conversation there is no fallthrough, but you can make use of |.

    This should do the trick:

    i match {
      case 1  => a    
      case 2 | 15 => b
                     c
      case _ => foo        
    } 
    
    0 讨论(0)
  • 2020-12-17 08:14

    While not applicable here, for more complex problems you can 'fallthrough' in a sense using the andThen function on partial functions.

     def do_function_a() { println("a"); }
     def do_function_b() { println("b"); }
     val run_function:PartialFunction[String, String] = { 
           case "a" => do_function_a(); "b"
           case "b" => do_function_b(); "c"
     }
    
     (run_function andThen run_function)("a") // a\nb
    
    0 讨论(0)
  • 2020-12-17 08:23

    If you are dealing with actual classes (instead of strings or ints), you need _: before each class to make them into a pattern before joining them with |.

    sealed trait ShipCondition
    case class ShipOnFire() extends ShipCondition
    case class FoodSucks() extends ShipCondition
    case class MateySnoresTooLoud() extends ShipCondition
    case class Ok() extends ShipCondition
    
    val condition = ShipOnFire()
    
    def checkCondition(cond: ShipCondition): Unit = {
      cond match {
        case c @ (_: ShipOnFire | _: FoodSucks) => println("Abandon Ship!") // can also use `c` for something. It has the type ShipCondition
        case (_: MateySnoresTooLoud | _: Ok) => println("Deal with it!")
      }
    }
    
    checkCondition(condition) // Abandon Ship!
    

    You get nice exhaustive checking too! Note that you cannot do case class destructuring when using alternative pattern matching (e.g. case (MateySnoresTooLoud(str) | _: Ok) => will fail to compile.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题