Scala, which continues to match the following cases after a successful match

How can I do in the switch scala statement, which, after starting one case block, starts another case block. (in java: cases without a break).

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

Thanks for the help!

+3
source share
3 answers

If you cannot use 0 | 1 | 2, you can use the action list as a workaround:

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
+4
source
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 performance is not critical, this should be good.

+4
source

Scala . (|) :

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

All Articles