问题描述
使用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))
万岁!这很好。但是,当我尝试对map
个Future
进行一次相同的操作时,为什么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
Future
和Seq
都定义了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))))