如何将 Seq[Try] 转换为 Try[Seq] [英] How to transform a Seq[Try] to a Try[Seq]
问题描述
使用Futures
,有一种简单的方法可以将Seq[Future]
转换为Future[Seq]
:
Future.sequence(seqOfFutures)
我用 Try
找不到类似的东西.
它适用于 foldLeft
,但我真正喜欢的是 Try.sequence(seqOfTry)
.
不提供这样的功能是不是有原因?
这是如何正确完成的?
语义:
成功值列表:Success(Seq(1,2,3,4))
对于失败有两种可能:
第一次失败
Failure
并返回它.这是由这个问题处理的:listtryt-to-trylistt-in-scala>收集所有
Failure
并返回复合"失败.
对于'复合'失败还有解决方案吗?
根据 Luis 的建议 Validated
专为错误累积而设计,因此请考虑 traverse
像这样
la.traverse(_.toEither.toValidatedNec)lb.traverse(_.toEither.toValidatedNec)
哪个输出
res2:cats.data.ValidatedNec[Throwable,List[Int]] = Invalid(Chain(java.lang.RuntimeException:boom, java.lang.RuntimeException: crash))res3:cats.data.ValidatedNec[Throwable,List[Int]] = Valid(List(1, 2, 3))
哪里
importcats.syntax.traverse._导入cats.instances.list._导入cats.syntax.either._导入 scala.util.{失败,成功,尝试}val la: List[Try[Int]] = List(Success(1), Success(2), Failure(new RuntimeException("boom")), Success(3), Failure(new RuntimeException("crash")))val lb: List[Try[Int]] = List(Success(1), Success(2), Success(3))
<小时>
没有错误累积,我们可以像这样排序
导入cats.implicits._序列
哪个输出
res0: scala.util.Try[List[Int]] = Failure(java.lang.RuntimeException:boom)
With Futures
there is an easy way to transform Seq[Future]
to a Future[Seq]
:
Future.sequence(seqOfFutures)
I could not find an analog thing with Try
.
It works with foldLeft
but what I really like would have something like Try.sequence(seqOfTry)
.
Is there a reason that such a function is not provided?
How is this done properly?
Semantics:
A List of the values on Success: Success(Seq(1,2,3,4))
For Failure there are 2 possibilities:
Fails on the fist
Failure
and returns it. This is handled by this question: listtryt-to-trylistt-in-scalaGathers all
Failures
and returns a 'compound' Failure.
Is there also a solution for the 'compound' Failure?
As per Luis' suggestion Validated
is designed for error accumulation so consider traverse
like so
la.traverse(_.toEither.toValidatedNec)
lb.traverse(_.toEither.toValidatedNec)
which outputs
res2: cats.data.ValidatedNec[Throwable,List[Int]] = Invalid(Chain(java.lang.RuntimeException: boom, java.lang.RuntimeException: crash))
res3: cats.data.ValidatedNec[Throwable,List[Int]] = Valid(List(1, 2, 3))
where
import cats.syntax.traverse._
import cats.instances.list._
import cats.syntax.either._
import scala.util.{Failure, Success, Try}
val la: List[Try[Int]] = List(Success(1), Success(2), Failure(new RuntimeException("boom")), Success(3), Failure(new RuntimeException("crash")))
val lb: List[Try[Int]] = List(Success(1), Success(2), Success(3))
Without error accumulation we could just sequence like so
import cats.implicits._
la.sequence
which outputs
res0: scala.util.Try[List[Int]] = Failure(java.lang.RuntimeException: boom)
这篇关于如何将 Seq[Try] 转换为 Try[Seq]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!