匹配“fallthrough":为多个案例执行同一段代码? [英] Match "fallthrough": executing same piece of code for more than one case?
本文介绍了匹配“fallthrough":为多个案例执行同一段代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Scala 的编写以下代码的方式是什么:
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
}
似乎不太合适,因为 Scala 根据第一个匹配情况评估匹配值,即如果 i=2,代码将不返回任何内容.
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.
感谢您的帮助!
推荐答案
根据 本次对话没有落差,但您可以使用|
.
According to this conversation there is no fallthrough, but you can make use of |
.
这应该可以解决问题:
i match {
case 1 => a
case 2 | 15 => b
c
case _ => foo
}
这篇关于匹配“fallthrough":为多个案例执行同一段代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文