首页 > 解决方案 > Scala - 是否有映射 Seq[A] => Seq[Either[Throwable, B]] 的函数?

问题描述

我正在寻找一个coll: Seq[A]在应用函数f: A => B并返回 a时映射集合的函数,Seq[Either[Throwable, B]]以便可以在下游处理错误。

是否有类似的功能预烘焙到某个库中?也许是 Cats 或 Scalaz?

请参阅下面的我的实现:

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))
  }
}

标签: scalascalazscala-catsmap-functioneither

解决方案


jwvhcoll.map(a => Try(f(a)).toEither)似乎是完成此任务的最简单/最干净的方法。


推荐阅读