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

前端 未结 8 1392
孤城傲影
孤城傲影 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:15

    Given a starting sequence xs, here's my take:

    xs collectFirst { case x@Left(_) => x } getOrElse
      Right(xs collect {case Right(x) => x})
    

    This being in answer to the body of the question, obtaining only the first error as an Either[String,Seq[A]]. It's obviously not a valid answer to the question in the title


    To return all errors:

    val lefts = xs collect {case Left(x) => x }
    def rights = xs collect {case Right(x) => x}
    if(lefts.isEmpty) Right(rights) else Left(lefts)
    

    Note that rights is defined as a method, so it'll only be evaluated on demand, if necessary

提交回复
热议问题