How to reduce Seq[Either[A,B]] to Either[A,Seq[B]]?

前端 未结 8 1395
孤城傲影
孤城傲影 2020-12-05 01:31

Given a sequence of eithers Seq[Either[String,A]] with Left being an error message. I want to obtain an Either[String,Seq[A]] where I

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 02:16

    It should work:

    def unfoldRes[A](x: Seq[Either[String, A]]) = x partition {_.isLeft} match {
      case (Seq(), r) => Right(r map {_.right.get})
      case (l, _) => Left(l map {_.left.get} mkString "\n")
    }
    

    You split your result in left and right, if left is empty, build a Right, otherwise, build a left.

提交回复
热议问题