tags:

views:

122

answers:

2

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

 int i;

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

   case 2:
   case 15:
        b();
        c();
        break;

   default: foo()        
 } 

I.e. what is the idiomatic way of executing the same piece of code based on multiple case values?

 i match {
   case 1  => a    
   case 2  =>
   case 15 => { b
                c }
   case _ => foo        
 } 

Doesn't quite seem do the trick, since Scala evaluates the match value based on the first matching case, i.e. if i=2 the code will return nothing.

Thanks for help!

+13  A: 

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        
} 
middus
Works like a treat! Thanks!
Totophil
I removed `{` and `}` around `b` and `c`, to make it clear they are unnecessary.
Daniel
+2  A: 

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.

Aaron
Note that if you prefer, there is no need for parentheses surrounding the guard condition in a `case ...` clause.
Randall Schulz