I am looking for a function that will map over a collection coll: Seq[A]
while applying a function f: A => B
and returning a Seq[Either[Throwable, B]]
so that errors can be handled downstream.
Is there a function similar to this that is pre-baked into some library? Perhaps Cats or Scalaz?
See my implementation below:
import cats.syntax.either._
def eitherMap[A,B](f: A => B, coll: Seq[A]): Seq[Either[Throwable, B]] = {
coll.map { elem =>
Either.catchNonFatal(f(elem))
}
}
Per jwvh: coll.map(a => Try(f(a)).toEither)
seems to be the simplest/cleanest way to accomplish this.