简化大规模匹配案例 - Scala

问题描述 投票:1回答:4

所以在其中一个地方我们有这个巨大的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
}

但我不想这样做

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:这些例子仅用于说明目的。我绝对不会尝试将字符串与整数相匹配

scala switch-statement pattern-matching refactoring match
4个回答
9
投票

如果你想简单地组合你的匹配,你可以注意到这些实际上是部分函数(因为匹配可能会失败):

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")

在这个例子中应该以相同的方式工作。


1
投票

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

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()方法中。


0
投票

您可以按照以下方式组织它

  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")
      })
    )
  }

0
投票

您可以尝试使用隐藏unapply方法中某些逻辑的提取器对象。没有你的实际代码,很难回答得更好。你能分享一下你的实际cases描述他们的“重复”性质吗?

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) => ???
  }
© www.soinside.com 2019 - 2024. All rights reserved.