【问题标题】:Pattern matching with OR logic使用 OR 逻辑进行模式匹配
【发布时间】:2018-06-28 06:23:44
【问题描述】:

例如,我有两个 Try 对象。如果一个或另一个失败,我想得到错误并以相同的方式处理它:

  val t1 = Try(throw new Exception("one"))
  val t2 = Try(throw new Exception("two"))

  (t1, t2) match {
    case (Success(_), Success(_)) => println("It's ok")
    case _ : Failure(e), _) | (_, Failure(e) =>  // Compile error here

      println("Fail", e)                         // Doesn't matter from where e was come 
  }

是否可以在两个失败选项中使用相同的e 编译这段代码?

【问题讨论】:

  • 你不能——你可以把期货放在一个列表中并像stackoverflow.com/questions/15495678/flatten-scala-try一样将其展平
  • 把两个失败的案例分开是不是很糟糕? case (Failure(e), _) => println(s"Fail $e") case (_, Failure(e)) => println(s"Fail $e")
  • @mfirry 其实,不是很糟糕,但我想知道这是否可能。

标签: scala pattern-matching


【解决方案1】:

您不能以这种方式组合匹配模式。您可以通过这种方式实现所需的行为:

t1.flatMap(_ => t2) match {
   case Success(_) => println("It's ok")
   case Failure(e) => prinltn("Fail", e)
}

【讨论】:

  • 有趣的技术。谢谢!
【解决方案2】:

基于@Nyavro answer 的另一种方便的方法是将多个tryes 组合在一个try via 中以获得理解:

 val tryDoIt = for {
   t1 <- Try(throw new Exception("one"))
   t2 <- Try(throw new Exception("two"))
   t3 <- Try(throw new Exception("three"))
 } yield (t1, t2, t3)

 tryDoIt match {
   case Success((x, y, z)) => println(x,y,z)
   case Failure(e) => println(e.getMessage)
 }

【讨论】:

    猜你喜欢
    • 2016-10-24
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2013-02-27
    • 2013-04-05
    • 1970-01-01
    相关资源
    最近更新 更多