scala - 将两个匹配模式合而为一

标签 scala

一个如何(以一种很好的方式)组合两个Scala match's?

首先,我必须测试Option是否为有效值:

myOption match {
  case Some(op) =>
    doSomethingWith(op)
  case None =>
    handleTheError()


然后,如果op有效,我想测试另一种模式:

Path(request.path) match {
  case "work" => {
    println("--Let's work--")

  }
  case "holiday" => {
    println("--Let's relax--")
  }
  case _ => {
    println("--Let's drink--")
  }
}


我可以这样合并它们:

myOption match {
  case Some(op) =>
    doSomethingWith(op)
    Path(request.path) match {
      case "work" => {
        println("--Let's work--")          
      }
      case "holiday" => {
        println("--Let's relax--")
      }
      case _ => {
        println("--Let's drink--")
      }
    }
  case None =>
    handleTheError()


但是,感觉草率。有没有更好的方法将它们以某种方式组合在一起。

更新资料

抱歉,我应该解释得更好。我实际上是在尝试找出是否存在用于简化(或分解)这些控制结构的已知模式。例如(想象这是真的):

x match {
 case a => {
   y match {
    case c => {}
    case d => {}
   }
 }
 case b => {}
}


等于

x -> y match {
  case a -> c => {}
  case a -> d => {}
  case b => {}
}


我只是在徘徊,是否有人已经确定了一些控制流的重构模式,就像代数中的2(x + y) = 2x + 2y

最佳答案

你可以做

myOption map { success } getOrElse handleTheError


或使用scalaz

myOption.cata(success, handleTheError)


其中success类似于

def success(op: Whatever) = {
  doSomethingWith(op)
  Path(request.path) match {
    case "work"    => println("--Let's work--")
    case "holiday" => println("--Let's relax--")
    case _         => println("--Let's drink--")      
  }
}


更新资料

您的伪代码

x -> y match {
  case a -> c => {}
  case a -> d => {}
  case b => {}
}


可以从字面上翻译为scala

(x, y) match {
  case (a, c) => {}
  case (a, d) => {}
  case (b, _) => {}
}


如果内部匹配器只有很少的选项(在这种情况下为cd),它看起来不错(这可能就是您想要的),但是它会导致代码重复(重复模式a)。因此,通常我更喜欢map {} getOrElse {}或较小功能上的模式匹配器分隔。但我重复一遍,在您的情况下,这看起来很合理。

关于scala - 将两个匹配模式合而为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9500906/

相关文章:

algorithm - 查找具有给定总和的子数组

scala - 处理极大数据时设备上没有剩余空间

scala - 定义投影以映射到嵌套案例类

scala - spark 是否优化应用于 RDD 的多个过滤器?

scala - 如何找到HDFS上存在的文件的正确URI

scala - Scala 中忽略变量语法的用例是什么?

scala - Scala 中的单位与无单位

scala读取大文件

java - Apache Spark MLlib : OLS regression in Java

scala - 专门集合中的 AnyVal 元素是否需要装箱?