scala是否支持许多模式匹配的一个默认子句?

时间:2015-05-27 08:14:30

标签: scala pattern-matching

考虑以下代码:

val first = ...
val second = ...
val third = ...
val fours = ...

first match {
  case "someString" => second match {
    case s:String => third match {
      case MyEnum.A => //some logic
      case MyEnum.B => fours match {
        case Some(old:String) => //some other logic
        case default=> defaulLogic
      }
      case default=> defaulLogic
    }
    case default=> defaulLogic
  }
  case default=> defaulLogic
}

private def defaulLogic()= {
    //log error here
}

有没有办法将case default逻辑放在一个地方而不是在每个模式匹配中重复它?

注意

只有match-case个参数的顶部,实际上还有更多的情况。

3 个答案:

答案 0 :(得分:8)

我会重写代码以便于阅读:

(first, second, third, fours) match {
  case ("something", s: String, MyEnum.A, _) => //some logic
  case ("something", s: String, MyEnum.B, Some(old)) => //some other logic
  case _ => defaulLogic
}

如果以这种方式编写,默认情况将以更自然的方式编写。

答案 1 :(得分:-1)

不是最优雅的想法,但是......

try {
  first match {
    case "someString" => second match {
      case s:String => third match {
        case MyEnum.A => //some logic
        case MyEnum.B => fours match {
          case Some(old:String) => //some other logic
        }
      }
    }
  }
} catch {
  case me : MatchError => defaultLogic
}

答案 2 :(得分:-1)

这有点优雅:)

Try{
  first match {
    case "someString" => second match {
    case s:String => third match {
      case MyEnum.A => //some logic
      case MyEnum.B => fours match {
        case Some(old:String) => //some other logic
      }
    }
  }
}.getOrElse(defaultLogic)