如何将[Future [A],Future [B]]转换为Future [Either [A,B]] [英] How to transform Either[Future[A], Future[B]] to Future[Either[A, B]]

查看:181
本文介绍了如何将[Future [A],Future [B]]转换为Future [Either [A,B]]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

由于我之前的问题解决方案

已经从注释中整理了答案,以方便读者:

1:由@wheaties&提供,您可以在纯scala中使用它(此处使用cats.Functor进行定义). @ 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:猫bisequence由于导入冲突而拒绝编译:这里一次导入就足够了-@kolmar提供

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

3:阅读 cats导入指南以避免将来出现此问题-礼貌@ peter-neyens

I have an instance of Either[Future[A], Future[B]] and I would like to transform it to 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.

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]]

Widening the imports to *.all._ did not change the compiler error.

I am on scala 2.11.8 as not all libraries the project depends upon have released a version for 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

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

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

3: read the cats import guide to avoid the issue in the future - courtesy @peter-neyens

这篇关于如何将[Future [A],Future [B]]转换为Future [Either [A,B]]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆