0

I have a value of this type:

List[Either[Error, Files]]

and I have a function which checks if there are any errors like this:

  private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
    if(result.exists(p => p.isLeft)){
      Left(Error("some downloads failed"))
    }else{
      Right(
      Right(
        result.collect {
          case Right(value) => value
        }
      )

    }

  }

Is this the best way to return the List of files if there are no errors in result?

3 Answers 3

5

There's a cats libarary which has sequence extension method for doing such thing https://gist.github.com/gbersac/14114f8bf8d0b1c6ea455aacdee0fcd8.

1
  • 1
    @Mojo Note that sequence === traverse(id) so if you got your List[Either[Error, Files]] from a map you can data.traverse(f) instead of data.map(f).sequence Commented Feb 18, 2020 at 12:06
2

Here is a solution that uses partition:

private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] =
  result.partition(_.isLeft) match {
    case (Left(error)::_, _) =>
      Left(error)
    case (_, r) =>
      Right(r.collect{ case Right(r) => r })
  }

This recursive version is more efficient but perhaps less clear:

private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
  @annotation.tailrec
  def loop(rem: List[Either[Error, Files]], res: List[Files]): Either[Error, List[Files]] =
    rem match {
      case Left(error) :: _ =>
        Left(error)
      case Right(file) :: tail =>
        loop(tail, file +: res)
      case _ =>
        Right(res.reverse)
    }

  loop(result, Nil)
}
0

You can use foldLeft in this case, to collect either all errors or all files. I don't know how Error looks like, but suppose it is simple case class with message string inside:

case class Error(message: String) {
  def append(message: Error): Error = copy(message = message + s"; ${message.message}")
}

def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
  val init: Either[Error, List[Files]] = Right(Nil)
  result.foldLeft(init) {
    case (Left(allErrors), Left(currentError)) => Left(allErrors.append(currentError))
    case (Left(allErrors), Right(_)) => Left(allErrors)
    case (Right(_), Left(currentError)) => Left(currentError)
    case (Right(allFiles), Right(currentFile)) => Right(currentFile :: allFiles)
  }
}

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.