使用猫嵌套映射一系列期货?
Mapping over a sequence of Futures using cats Nested?
使用 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, Option, String] = Nested(List(Some("1"), None))
万岁!这很好用。但是,当我尝试对 Future
的 Seq
uences 做同样的事情时,为什么 map
不存在?
@ 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,List,Int]
did you mean mapK?
val res5 = nestedFutureSeq.map(_.toString)
^
Compilation Failed
Future
和 Seq
都定义了 map
,所以这似乎是可能的。我可以使用 Nested
来执行此操作吗?如果可以,如何操作?
map
on Nested 如果两种类型都有一个 Functor 的实例。
并且 Future 的 Functor 需要和 implicit
ExecutionContext 在范围内,因为所有方法在未来需要它。
因此,如果您添加这样一行 (或将隐式 ec 放入范围的任何其他形式):
import scala.concurrent.ExecutionContext.Implicits.global
你会得到你想要的结果。
nestedFutureSeq.map(_.toString)
// res: Nested[Future, List, String] = Nested(Future(Success(List(1))))
使用 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, Option, String] = Nested(List(Some("1"), None))
万岁!这很好用。但是,当我尝试对 Future
的 Seq
uences 做同样的事情时,为什么 map
不存在?
@ 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,List,Int]
did you mean mapK?
val res5 = nestedFutureSeq.map(_.toString)
^
Compilation Failed
Future
和 Seq
都定义了 map
,所以这似乎是可能的。我可以使用 Nested
来执行此操作吗?如果可以,如何操作?
map
on Nested 如果两种类型都有一个 Functor 的实例。
并且 Future 的 Functor 需要和 implicit
ExecutionContext 在范围内,因为所有方法在未来需要它。
因此,如果您添加这样一行 (或将隐式 ec 放入范围的任何其他形式):
import scala.concurrent.ExecutionContext.Implicits.global
你会得到你想要的结果。
nestedFutureSeq.map(_.toString)
// res: Nested[Future, List, String] = Nested(Future(Success(List(1))))