Java – after successful matching, continue to match the scala switch of the next case
•
Java
How to execute another case block after executing one case block in a Scala switch statement (in Java: no interruption)
switch(step) {
case 0: do something;
case 1: do something more;
case 2: etc...;
break;
default: do something else;
}
Thanks for your help!
Solution
If you cannot use 0 | 1 | 2, you can use the action list as a solution, as shown below:
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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
