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

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

提交回复
热议问题