字符串序列中值的 Scala 模式匹配

scala pattern matching on value in sequence of strings

变量 someKey 可以是“a”、“b”或“c”。

我能做到:

someKey match {
    case "a" => someObjectA.execute()
    case "b" => someOther.execute()
    case "c" => someOther.execute()
    case _ => throw new IllegalArgumentException("Unknown")
}

我怎样才能压缩这个模式匹配,这样我就可以用例如Seq("b", "c") 如果它在序列中则将两行模式匹配替换为一行?

编辑:

someKey match {
        case "a" => someObjectA.execute()
        case someKey if Seq("b","c").contains(someKey) => someOther.execute()
        case _ => throw new IllegalArgumentException("Unknown")
    }

对于这种特殊情况,我可能会去

// likely in some companion object so these get constructed once
val otherExecute = { () => someOther.execute() }
val keyedTasks = Map(
  "a" -> { () => someObjectA.execute() },
  "b" -> otherExecute,
  "c" -> otherExecute
)

// no idea on the result type of the execute calls?  Unit?
def someFunction(someKey: String) = {
  val resultOpt = keyedTasks.get(someKey).map(_())

  if (resultOpt.isDefined) resultOpt.get
  else throw new IllegalArgumentException("Unknown")
}

您可以在 case 子句中使用“或”:

someKey match {
    case "a" => someObjectA.execute()
    case "b"|"c" => someOther.execute()
    case _ => ???
}