[英]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")
}
如何壓縮此模式匹配,以便我可以檢查 someKey 是否與例如 Seq("b", "c") 以及它是否在序列中,然后將兩行模式匹配替換為一行?
編輯:
someKey match {
case "a" => someObjectA.execute()
case someKey if Seq("b","c").contains(someKey) => someOther.execute()
case _ => throw new IllegalArgumentException("Unknown")
}
您可以在case
子句中使用“或”:
someKey match {
case "a" => someObjectA.execute()
case "b"|"c" => someOther.execute()
case _ => ???
}
對於這種特殊情況,我可能會 go 到
// 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")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.