考虑以下使用ScalaZ的OptionT
:
val answer = for {
customer <- optionT(function1(codeString))
customerId <- someOptionT(Future(Seq(function2(customer)))
alerts <- someOptionT(Future.sequence(function3(customerId))
} yield alerts
function1
返回Future[Option[Customer]]
function2
返回String
function3
返回Seq[Future[Option[String]]]
同时这是someOptionT
def someOptionT[T](t: Future[T]): OptionT[Future, T] = optionT[Future](t.map(Some.apply))
我在for
理解的最后一行(alerts
)得到以下异常:
could not find implicit value for parameter F: scalaz.Functor[scala.concurrent.Future]
知道为什么?
答案 0 :(得分:8)
错误消息完全不清楚,但问题与在REPL中编写myFuture.map(whatever)
而在范围内没有隐式执行上下文完全相同。
scala> import scala.concurrent.Future
import scala.concurrent.Future
scala> def foo(myFuture: Future[Int]) = myFuture.map(_ + 1)
<console>:8: error: Cannot find an implicit ExecutionContext. You might pass
an (implicit ec: ExecutionContext) parameter to your method
or import scala.concurrent.ExecutionContext.Implicits.global.
def foo(myFuture: Future[Int]) = myFuture.map(_ + 1)
^
Scalaz为Functor
提供了Monad
(以及Future
等),但您必须拥有执行上下文才能获得它们。导入global
(或以其他方式提供),你会没事的。