使用嵌套的猫在一系列期货上进行映射?

问题描述

使用Ammonite REPL,我能够重现这部分猫Nested code example

@ import $ivy.`org.typelevel::cats-core:2.0.0`; import cats.Functor; import cats.data.Nested; import cats.implicits._; import scala.concurrent.Future;

@ val nested = Nested(List(Some(1),None))
nested: Nested[List,Option,Int] = Nested(List(Some(1),None))

@ nested.map(_.toString)
res2: Nested[List,String] = Nested(List(Some("1"),None))

万岁!这很好。但是,当我尝试对mapFuture进行一次相同的操作时,为什么Seq不存在?

@ val nestedFutureSeq = Nested(Future.successful(List(1)))
nestedFutureSeq: Nested[Future,List,Int] = Nested(Future(Success(List(1))))

@ nestedFutureSeq.map(_.toString)
cmd5.sc:1: value map is not a member of cats.data.Nested[scala.concurrent.Future,Int]
did you mean mapK?
val res5 = nestedFutureSeq.map(_.toString)
                           ^
Compilation Failed

FutureSeq都定义了map,因此看来这是可能的。我可以使用Nested来做到这一点吗?如果可以,怎么办?

解决方法

如果两种类型都有 Functor 的实例,则嵌套上的

map将起作用。
并且 Future Functor 要求和范围内的implicit ExecutionContext ,因为 Future 中的所有方法都需要它。

因此,如果您添加这样的一行(或在范围内放置隐式ec的任何其他形式)

import scala.concurrent.ExecutionContext.Implicits.global

您将获得预期的结果。

nestedFutureSeq.map(_.toString)
// res: Nested[Future,List,String] = Nested(Future(Success(List(1))))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...