简体   繁体   English

如何将[未来[A],未来[B]]转换为未来[[A,B]]

[英]How to transform Either[Future[A], Future[B]] to Future[Either[A, B]]

I have an instance of Either[Future[A], Future[B]] and I would like to transform it to Future[Either[A, B]] . 我有一个Either[Future[A], Future[B]]的实例,我想将它转换为Future[Either[A, B]]

Since my previous question , cats 0.8.1 has been released, changing the structure of the library and dropping Xor in favor of Either , which is right-biased in 2.12. 自从我上一个问题以来,已经发布了cat 0.8.1 ,改变了库的结构并放弃了Xor ,转而使用了Either ,这在2.12中是正确的。

Thus the method described in the previous accepted answer does not work anymore. 因此,先前接受的答案中描述的方法不再起作用。 I have tried to find the appropriate imports but failed. 我试图找到合适的进口但失败了。

cats.instances.either._
cats.implicits._ 
cats.syntax.bitraverse._

looked plausible but unfortunately does not work. 看起来似乎有道理,但遗憾的是无法正常工作。 Compilation still fails with value bisequence is not a member of Either[scala.concurrent.Future[A],scala.concurrent.Future[‌​B]] 编译仍然失败, value bisequence is not a member of Either[scala.concurrent.Future[A],scala.concurrent.Future[‌​B]]

Widening the imports to *.all._ did not change the compiler error. 将导入扩展为*.all._并未更改编译器错误。

I am on scala 2.11.8 as not all libraries the project depends upon have released a version for 2.12 我在scala 2.11.8上,因为项目所依赖的所有库都没有发布2.12版本

have compiled the answers from the comments for reader convenience: 为了方便读者,我们从评论中汇总了答案:

1: you can do it in plain scala (using cats.Functor for the definition here), courtesy of @wheaties & @jean-philippe-pellet 1:你可以在普通的scala中使用(在这里使用cats.Functor进行定义),由@wheaties和@ jean-philippe-pellet提供

def eitherFmap[F[_], A, B](either: Either[F[A], F[B])(implicit F: Functor[F]): F[Either[A, B]] =   
either.fold(f => F.map(f)(Left(_)), f => F.map(f)(Right(_)))

2: cats bisequence refused to compile because of conflicting imports: a single import is enough here - courtesy of @kolmar 2:由于进口冲突,猫的bisequence拒绝编译:这里只需一次进口 - @kolmar提供

import cats.instances._
...
val futureOfEither = eitherOfFutures.bisequence

3: read the cats import guide to avoid the issue in the future - courtesy @peter-neyens 3:阅读猫进口指南以避免将来出现问题 - 礼貌@ peter-neyens

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM