Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

scala - How to transform a Seq[Try] to a Try[Seq]

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-scala

  • Gathers all Failures and returns a 'compound' Failure.

Is there also a solution for the 'compound' Failure?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...