What is the Scala\'s way to write the following code:
int i;
switch(i) {
case 1:
a();
break;
case 2:
case 15:
b();
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.