Flatten Scala Try

后端 未结 7 1025
天命终不由人
天命终不由人 2020-12-14 19:20

Is there a simple way to flatten a collection of try\'s to give either a success of the try values, or just the failure? For example:

def map(l:List[Int]) =          


        
7条回答
  •  一整个雨季
    2020-12-14 20:19

    These are my 2cents:

    def sequence[A, M[_] <: TraversableOnce[_]](in: M[Try[A]])
      (implicit cbf:CanBuildFrom[M[Try[A]], A, M[A]]): Try[M[A]] = {
        in.foldLeft(Try(cbf(in))) {
          (txs, tx) =>
            for {
              xs <- txs
              x <- tx.asInstanceOf[Try[A]]
            } yield {
              xs += x
            }
        }.map(_.result())
      }
    

提交回复
热议问题