Scala switch which continue matching next cases af

2020-03-05 03:33发布

问题:

How can I do in scala switch statement which after performing one case block start perform another case block. (in java: cases without break).

switch(step) {
    case 0: do something;
    case 1: do something more;
    case 2: etc...;
            break;
    default: do something else;
}

Thanks for help!

回答1:

In case you can't use 0 | 1 | 2 you could use a list of actions as workaround like this:

def switch[T](i: T)(actions: (T, () => Unit)*)(default: => Unit) = {
  val acts = actions.dropWhile(_._1 != i).map{_._2}
  if (acts.isEmpty) default
  else acts.foreach{_()}
}

def myMethod(i: Int): Unit = 
  switch(i)(
    0 -> {() => println("do 0")},
    1 -> {() => println("do 1")},
    2 -> {() =>
      println("do 2")
      return // instead of break
    },
    3 -> {() => println("do 3")}
  )(default = println("do default"))


myMethod(1)
// do 1
// do 2

myMethod(3)
// do 3    

myMethod(5)
// do default


回答2:

def myMatch(step: Int): Int = step match {
  case 0 => { dosomething(); myMatch(step + 1) }
  case 1 => { dosomethingMore(); myMatch(step + 1) }
  case 2 => etc()
  case _ => doSomethingElse();
}

If the performance isn't critical, this should be fine.



回答3:

In Scala, there is no switch case fall through. You can do or (|) instead:

step match {
  case 0 | 1 | 2 => something
  ...
}