List[Try[T]] to Try[List[T]] in Scala

前端 未结 4 1077
天涯浪人
天涯浪人 2021-01-20 22:04

I would like to know how to convert a List[Try[T]] into Try[List[T]] in Scala?

I have tried using an accumulator and folding right but it do

4条回答
  •  爱一瞬间的悲伤
    2021-01-20 22:14

    Cats is a nice way to go but it can be done via the Standard Library without too much complication.

    import util.{Try, Success, Failure}
    
    def seqnc[T](lst :List[Try[T]]) :Try[List[T]] =
      lst.foldRight(Try(List.empty[T])) {
        case (tt, acc) => for { t <- tt
                                a <- acc
                              } yield t :: a
      }
    

提交回复
热议问题