匹配“贯穿性”:对多个案例执行同一段代码?

什么是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 2 => case 15 => { b c } case _ => foo } 

似乎没有什么窍门,因为Scala基于第一个匹配的情况评估匹配值,即如果i = 2,则代码将不返回任何内容。

感谢帮助!

根据这个谈话没有失败,但你可以利用|

这应该做的伎俩:

 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中的标准开关语句提供了更多的function。

虽然在这里不适用,但对于更复杂的问题,您可以在部分函数上使用andThen函数,从某种意义上讲,可以“穿越”。

  def do_function_a() { println("a"); } def do_function_b() { println("b"); } val run_function:PartialFunction[String, String] = { case "a" => do_function_a(); "b" case "b" => do_function_b(); "c" } (run_function andThen run_function)("a") // a\nb 

如果你正在处理实际的类(而不是string或整数),你需要_:在每个类之前使它们成为一个模式,然后join|

 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 (MateySnoresTooLoud(str) | _: Ok) =>将无法编译时,您不能执行case类解构。