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