Deb*_*rty 2 refactoring scala pattern-matching match switch-statement
因此,在其中一个地方,我们variable match case发表了如此宏伟的声明。
包含近150个不同的case语句
看起来很恐怖。
我想将其分解为较小的函数,可以将匹配项分成10个部分,然后将数字case语句减少到15个左右。这很好。
目前看起来像这样
massiveCaseVariable match {
case "one" => 1
case "two" => 2
case "three" => 3
case "four" => 4
case "five" => 5
case "six" => 6
}
Run Code Online (Sandbox Code Playgroud)
但是我不想这样
massiveCaseVariable match {
case "one" || "two" || "three" => firstCategory(massiveCaseVariable)
case "four" || "five" || "six" => secondCategory(massiveCaseVariable)
}
def firstCategory(caseVariable: String): Int =
caseVariable match {
case "one" => 1
case "two" => 2
case "three" => 3
}
def secondCategory(caseVariable: String): Int =
caseVariable match {
case "four" => 4
case "five" => 5
case "six" => 6
}
Run Code Online (Sandbox Code Playgroud)
太重复了。有没有更好,更简洁的方法来做到这一点?
我在Scala 2.11上
PS:这些示例仅用于说明目的。我绝对不是想将字符串匹配为整数
如果您想简单地组合匹配项,那么您会注意到这些实际上是部分函数(因为匹配可能会失败):
val firstCategory: PartialFunction[String, Int] = {
case "one" => 1
case "two" => 2
case "three" => 3
}
val secondCategory: PartialFunction[String, Int] = {
case "four" => 4
case "five" => 5
case "six" => 6
}
Run Code Online (Sandbox Code Playgroud)
可以结合使用:
val all = firstCategory orElse secondCategory
all("one")
Run Code Online (Sandbox Code Playgroud)
有趣的是,许多集合是部分函数,例如Map,所以:
val firstCategory = Map[String, Int](
"one" -> 1,
"two" -> 2,
"three" -> 3
)
val secondCategory = Map[String, Int](
"four" -> 4,
"five" -> 5,
"six" -> 6
)
val all = firstCategory ++ secondCategory
all("one")
Run Code Online (Sandbox Code Playgroud)
在此示例中应以相同的方式工作。