Scala模式匹配选项字符串

时间:2016-01-07 00:28:09

标签: scala

我有一个名为failureType的字符串选项。根据这个String的值,我必须决定我想要创建什么类型的对象。像 -

这样的东西
val failure: Option[FailureType] = failureType map (f => f.toLowerCase match {
          case "build" => FailureType.BuildFailure
          case "test" => FailureType.TestFailure
          case "service timeout" => FailureType.ServiceTimeout
          case "job timeout" => FailureType.JobTimeout
          case "work item timeout" => FailureType.WorkItemTimeout
        } )

我的问题是,如果我将“build”,“test”,“service timeout”,“job timeout”或“work item timeout”以外的值赋给failureType,则会出现Match Error。这是有道理的,因为我没有做任何默认捕获。所以我的问题是如何做这个默认捕获?如果我做

case _ => None

在其他案例陈述结束时,我会收到错误,因为我当然在Map中。我的另一个选择似乎是根本没有使用地图而是直接进行匹配 -

val failure: Option[FailureType] = failureType match {
          case Some("build") => FailureType.BuildFailure
          case Some("test") => FailureType.TestFailure
          case Some("service timeout") => FailureType.ServiceTimeout
          case Some("job timeout") => FailureType.JobTimeout
          case Some("work item timeout") => FailureType.WorkItemTimeout
          case _ => None
        }

但在这种情况下,我失去了不区分大小写匹配的能力。

3 个答案:

答案 0 :(得分:2)

我会使用flatMap - 让落后案例返回None,而有效案件会返回Some(_relevant_failure_type)

val failure: Option[FailureType] = failureType flatMap (f => f.toLowerCase match {
      case "build" => Some(FailureType.BuildFailure)
      case "test" => Some(FailureType.TestFailure)
      case "service timeout" => Some(FailureType.ServiceTimeout)
      case "job timeout" => Some(FailureType.JobTimeout)
      case "work item timeout" => Some(FailureType.WorkItemTimeout)
      case _ => None
    } )

答案 1 :(得分:2)

您要找的是.collect

val failure = failureType.map(_.toLowerCase).collect { 
   case "build" => FailureType.BuildFailure
   case "test" => FailureType.TestFailure
   case "service timeout" => FailureType.ServiceTimeout
   case "job timeout" => FailureType.JobTimeout
   case "work item timeout" => FailureType.WorkItemTimeout
}

.collect需要PartialFunction,如果在参数上定义了函数,则会返回其应用程序的结果,否则将返回None

答案 2 :(得分:2)

部分困难来自于尝试同时折叠案例和匹配。如果您先使用map (_.toLowerCase)折叠案例,则可以使用collect完全按照自己的意愿执行操作:

val failure: Option[FailureType] = failureType map (_.toLowerCase) collect {
  case "build" => FailureType.BuildFailure
  case "test" => FailureType.TestFailure
  case "service timeout" => FailureType.ServiceTimeout
  case "job timeout" => FailureType.JobTimeout
  case "work item timeout" => FailureType.WorkItemTimeout
}

对于未明确匹配的任何字符串,结果为None