我正在尝试使用Scalaz的应用程序构建器来简化一些并行运行少数未来的代码:
import scalaz._, Scalaz._
val fooF: Future [String] = myService.getFoo ()
val barF: Future [String] = myService.getBar ()
val resultF = for {
foo <- fooF
bar <- barF
}
yield { foo + bar }
我知道我应该能够像这样重写上面的代码:
val resultF = (myService.getFoo () |@| myService.getBar ()) {
(foo, bar) => { foo + bar }
}
但是我收到以下编译错误:
value |@| is not a member of scala.concurrent.Future[String]
我做错了什么?
答案 0 :(得分:5)
你需要在范围内有隐含的ExecutionContext,它需要构建Applicative for Future(以及Monad等)
import scalaz._, Scalaz._
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
val fooF: Future [String] = Future("aaa")
val barF: Future [String] = Future("bbb")
val result = (fooF |@| barF)((l, r) => s"$l$r")
println(Await.result(result, 10.seconds))
<强>更新强>
您可以在scalaz.std.Future.scala
中查看implicit def futureInstance(implicit ec: ExecutionContext): Monad[Future] with Cobind[Future] =
new FutureInstance