成功匹配后继续匹配下一个案例的 Scala 开关

2022-01-19 00:00:00 scala switch-statement java

如何在 scala switch 语句中执行一个 case 块开始执行另一个 case 块.(在 java 中:没有中断的情况).

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;
}

感谢您的帮助!

推荐答案

万一不能使用0 |1 |2 您可以使用操作列表作为解决方法,如下所示:

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

相关文章