【问题标题】:What is an idiomatic Scala way to do batch processing with exceptions什么是一种惯用的 Scala 方式来进行异常批处理
【发布时间】:2015-08-27 01:22:22
【问题描述】:

如果我有一个 List[Try[Int]] 表示函数的一些结果。

scala> import scala.util._
scala> val result = List[Try[Int]](
      Success(1),
      Failure(new RuntimeException("first exception")),
      Success(2),
      Failure(new RuntimeException("second exception")))

如果我只是收集成功,我会隐藏异常

scala> result.collect{case Success(x)=>x}
res1: List[Int] = List(1, 2)

我可以分区,但结果需要进一步处理

scala> val res2 = result.partition(_.isSuccess)
res2: (List[scala.util.Try[Int]], List[scala.util.Try[Int]]) = (List(Success(1), Success(2)),List(Failure(java.lang.RuntimeException: first exception), Failure(java.lang.RuntimeException: second exception)))

scala> res2._1.collect{case Success(x)=>x}
res6: List[Int] = List(1, 2)

scala> res2._2.collect{case Failure(x)=>x}
res7: List[Throwable] = List(java.lang.RuntimeException: first exception, java.lang.RuntimeException: second exception)

如果我有 List[Try[Option[Int]]],这会变得更加复杂。

【问题讨论】:

  • 你还没有描述你真正想对成功和失败做什么。您到底在寻找什么?
  • 验证仍然没有涵盖你想要成功和失败的情况。

标签: scala scala-collections idioms


【解决方案1】:

如果将List[Try[Int]] 转换为Try[List[Int]] 会怎样?

import scala.util.Try

val demo = List(Try(1),Try(2))

Try(demo.map(x => x.get))

List[Try[Option[Int]]] 也不会复杂。

希望我对您有所帮助。

【讨论】:

  • 这将返回列表中找到的第一个失败。在这种情况下,其他的将被隐藏,并且 Success(Int) 结果也被忽略。
  • 那么你就可以过滤掉像 res6.filter(_.isDefined) 这样的 Option 值,对于 res6: List[Int] = List(1, 2) 也不复杂。跨度>
猜你喜欢
  • 2013-01-04
  • 2021-09-17
  • 2021-10-01
  • 2018-09-11
  • 1970-01-01
  • 2017-03-30
  • 2020-12-16
  • 2018-08-09
  • 1970-01-01
相关资源
最近更新 更多