我最近开始使用Either[A, B]
,发现它非常有用。现在,我在当前项目中发现了一些样板代码。这是一个简化的版本:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def f1(): Future[Either[Throwable, String]] = Future {
Right("result 1")
}
def f2(): Future[Either[Throwable, String]] = Future {
Right("result 2")
}
def combine(): Future[String] = {
val result: Future[List[Either[Throwable, String]]] = Future.sequence(List(f1(), f2()))
result.map { stringList: List[Either[Throwable, String]] =>
stringList.map { either: Either[Throwable, String] =>
either match {
case Right(str) => str
case Left(e) => e
}
}
}
}
在两种情况下(f1
和f2
),它将返回一个Right("...")
。我想知道如果我有List[Either[Throwable, String]]
并想将其转换为Either[Throwable, List[String]]
,这样就不需要映射List[...]
并只需映射Either
直接加上一些抽象。