简化大规模匹配案例 - Scala



所以在其中一个地方,我们有这个巨大的variable match case语句。

包含近 150 个不同的case语句

看起来很可怕。

我想把它分解成更小的函数,我可以将匹配项分组为 10 个片段,然后语句的数量减少到大约 15 case个。这很好。

目前看起来像这样

massiveCaseVariable match {
  case "one" => 1
  case "two" => 2
  case "three" => 3
  case "four" => 4
  case "five" => 5
  case "six" => 6
}

但我不想这样做

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
  }

太重复了。有没有更好更简洁的方法可以做到这一点?

我在 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
  }

可以组合:

val all = firstCategory orElse secondCategory
all("one")

有趣的是,许多集合都是部分函数,例如 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")

在此示例中应以相同的方式工作。

您可以尝试使用提取器对象来隐藏unapply方法中的某些逻辑。如果没有您的实际代码,很难更好地回答。你能分享一些描述它们"重复"性质的实际case吗?

https://danielwestheide.com/blog/2012/11/21/the-neophytes-guide-to-scala-part-1-extractors.html

  trait Hierarchy
  class Case1(val s: String) extends Hierarchy
  object Case1 {
    def unapply(arg: Case1): Boolean = arg.s == "one" || arg.s == "two"
  }
  class Case2(val s: String) extends Hierarchy
  object Case2 {
    def unapply(arg: Case2): Boolean = arg.s == "three" || arg.s == "four" || arg.s == "five"
  }
  class Case3(val s: String) extends Hierarchy
  object Case3 {
    def unapply(arg: Case3): Option[String] = if (arg.s == "six" || arg.s == "seven") Some(arg.s) else None
  }
  class Case4(val s: String) extends Hierarchy
  object Case4 {
    // some other logic
    def unapply(arg: Case4): Option[(String, Int)] = if (arg.s == "eight") Some(arg.s, 8) 
                                                     else if (arg.s == "nine") Some(arg.s, 9) 
                                                     else None
  }
  val massiveCaseVariable: Hierarchy = ???
  massiveCaseVariable match {
    case Case1() => ???
    case Case2() => ???
    case Case3(s) => ???
    case Case4(s, n) => ???
  }

不要使用模式匹配,或者至少不要单独使用。

trait Handler {
def canHandle(variable: String): Boolean
def handle(variable: String): Int
}
class HandlerCategory1 extends Handler {/*...*/}
class HandlerCategory2 extends Handler {/*...*/}
// ...
val variable: String = ???
val handlers = List(new HandlerCategory1(), new HandlerCategory2())
handlers.find(_.canHandle(variable)).map(_.handle(variable))

您可以将模式匹配中的条件放入特定的canHandle()方法中。

您可以按以下方式组织它

  val all = firstCategory() ++ secondCategory()
  all("some").apply()
  def firstCategory() : Map[String, () => ()] = {
    Map(
      "first" -> (() => {}),
      "second" -> (() => {})
    )
  }
  def secondCategory(): Map[String, () => ()] = {
    Map(
      "third" -> (() => {
        print("some code")
      }),
      "forth" -> (() => {
        print("some other code")
      })
    )
  }

最新更新