Scala 匹配“;漏洞百出:为多个案例执行同一段代码?
Scala编写以下代码的方式是什么:Scala 匹配“;漏洞百出:为多个案例执行同一段代码?,scala,Scala,Scala编写以下代码的方式是什么: int i; switch(i) { case 1: a(); break; case 2: case 15: b(); c(); break; default: foo() } 即,基于多个case值执行同一段代码的惯用方式是什么 i match { case 1 => a case
int i;
switch(i) {
case 1:
a();
break;
case 2:
case 15:
b();
c();
break;
default: foo()
}
即,基于多个case值执行同一段代码的惯用方式是什么
i match {
case 1 => a
case 2 =>
case 15 => { b
c }
case _ => foo
}
这似乎不太管用,因为Scala根据第一个匹配的情况计算匹配值,即如果i=2,代码将不返回任何结果
谢谢你的帮助 根据,没有故障,但您可以使用
sealed trait ShipCondition
case class ShipOnFire() extends ShipCondition
case class FoodSucks() extends ShipCondition
case class MateySnoresTooLoud() extends ShipCondition
case class Ok() extends ShipCondition
val condition = ShipOnFire()
def checkCondition(cond: ShipCondition): Unit = {
cond match {
case c @ (_: ShipOnFire | _: FoodSucks) => println("Abandon Ship!") // can also use `c` for something. It has the type ShipCondition
case (_: MateySnoresTooLoud | _: Ok) => println("Deal with it!")
}
}
checkCondition(condition) // Abandon Ship!
这应该可以做到:
i match {
case 1 => a
case 2 | 15 => b
c
case _ => foo
}
Case语句实际上可以使用标准if语句包含额外的逻辑保护。所以你可以这样做:
i match {
case x if x == 1 => a
case x if (x == 2 | x == 15) => b; c;
case _ => foo
}
匹配的保护可以是任何布尔函数或函数的组合,因此它比Java中的标准switch语句具有更大的功能。虽然在这里不适用,但对于更复杂的问题,您可以在某种意义上在部分函数上使用andThen函数来“解决”
def do_函数_a(){println(“a”)}
def do_函数_b(){println(“b”);}
val run_函数:PartialFunction[String,String]={
案例“a”=>do_函数_a();“b”
案例“b”=>do_函数_b();“c”
}
(运行函数和第二个运行函数)(“a”)//a\nb
如果您处理的是实际的类(而不是字符串或整数),则需要在每个类之前添加:
,以便在将它们与|
连接之前将它们生成一个模式
sealed trait ShipCondition
case class ShipOnFire() extends ShipCondition
case class FoodSucks() extends ShipCondition
case class MateySnoresTooLoud() extends ShipCondition
case class Ok() extends ShipCondition
val condition = ShipOnFire()
def checkCondition(cond: ShipCondition): Unit = {
cond match {
case c @ (_: ShipOnFire | _: FoodSucks) => println("Abandon Ship!") // can also use `c` for something. It has the type ShipCondition
case (_: MateySnoresTooLoud | _: Ok) => println("Deal with it!")
}
}
checkCondition(condition) // Abandon Ship!
你也很好!请注意,当使用替代模式匹配时,您不能执行case类解构(例如,
case(mateysnorestoloud(str)|:Ok)=>
将无法编译。I已删除{
和}
围绕b
和c
,以明确它们是不必要的。谢谢你,Daniel。我自己没有考虑过这一点。很明显,但很容易出错,如果你愿意,在case…
子句中,不需要在保护条件周围加括号。