我有一个 Future[Either[A, B]]以及提供 Future[C] 的函数来自 B .
我需要转换 Future[Either[A, B]]至 Future[Either[A, C]] .
有没有直接获取Future[Either[A, C]]的方法而不是 Future[Either[A, Future[C]]] ?
我正在考虑类似的事情:
val eventuallyInitialValue: Future[Either[A, B]] = ???
val result: Future[Either[A, C]] = for {
e: Either[A, B] <- initialValue
c: C <- service.getValue(e.right)
} yield e.right.map(_ => c)
它只是伪代码,因为
service.getValue(e.right)不编译。什么是正确的做法?
请您参考如下方法:
这就是我想出的:
type B = Int
type A = String
type C = Long
val eitherF: Future[Either[A, B]] = ???
def f(b: B): Future[C] = ???
val mapped: Future[Either[A, C]] = eitherF.flatMap {
case Left(a) =>
Future.successful(Left(a))
case Right(b) =>
f(b).map(Right(_))
}
基本上可以
flatMap future ,如果是左,则返回成功,如果是右,则可以应用 future 并映射
Right到它。




