【问题标题】:How to transform Either[Future[A], Future[B]] to Future[Either[A, B]]如何将 Either[Future[A], Future[B]] 转换为 Future[Either[A, B]]
【发布时间】:2016-12-16 16:09:47
【问题描述】:

我有一个Either[Future[A], Future[B]] 的实例,我想将其转换为Future[Either[A, B]]

由于my previous questioncats 0.8.1 已发布,更改了库的结构并删除了Xor 以支持Either,这在2.12 中偏右。

因此,之前接受的答案中描述的方法不再起作用。我试图找到合适的进口但失败了。

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

看起来很合理,但不幸的是不起作用。 value bisequence is not a member of Either[scala.concurrent.Future[A],scala.concurrent.Future[‌​B]] 编译仍然失败

将导入范围扩大到 *.all._ 并没有改变编译器错误。

我使用的是 scala 2.11.8,因为并非该项目所依赖的所有库都发布了 2.12 版本

【问题讨论】:

  • either.fold(_.map(Left(_)), _.map(Right(_))),但这与猫有什么关系?
  • 我已经在猫 0.8.1 和 scala 2.11.8 和 2.12.1 上尝试过这个,Either[Future[A], Future[B]] 上的 bisequence 在这两个版本中都有效。范围内是否有隐含的ExecutionContextApplicative[Future] 需要它
  • 删除了我的答案。既然我发现Bitraverse 中的任何一个都有语法和实例,那么看起来您肯定缺少导入。尝试添加import cats.syntax.either._ 看看是否会继续前进。
  • 哦,我已经复制了你的问题。尝试只导入一次cats.implicits._。似乎您的导入相互干扰。
  • 留给后代:The Cats import guide

标签: scala applicative either scala-cats


【解决方案1】:

为方便读者,整理了来自 cmets 的答案:

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 由于导入冲突而拒绝编译:这里一个导入就足够了 - 由 @kolmar 提供

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

3:阅读cats import guide 以避免将来出现问题 - 礼貌@peter-neyens

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 2013-07-02
    • 2019-09-23
    • 1970-01-01
    • 2020-07-16
    • 2019-10-23
    相关资源
    最近更新 更多