Scalaz和scala.concurrent.Future

时间:2015-11-04 17:39:00

标签: scala scalaz

OptionT[Future[_], A]变换器在范围内需要隐式Functor[Future]。但是,如果将证据移动到另一个没有隐式ExecutionContext的文件,则编译器会因错误Cannot find an implicit ExecutionContext.而失败。是否有可能编写一个在整个地方都没有证据定义的代码,并且会使用ExecutionContext时调用的OptionT

import scala.concurrent.{Await, Future}
import scalaz._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

object Hello {
  implicit val ev = new Functor[scala.concurrent.Future] {
    override def map[A, B](fa: Future[A])(f: (A) => B): Future[B] = fa.map(f)
  }

  def main(args: Array[String]): Unit = {
    val task: Future[Option[String]] = Future { Some("hello") }
    val scream = (for( message <- OptionT(task)) yield message.toUpperCase()).run
    val msg = Await.result(scream, 10.seconds)
    println(msg.get)
  }
}

1 个答案:

答案 0 :(得分:2)

证据需要执行上下文:

implicit def ev (implicit ec: ExecutionContext) = 
  new Functor[scala.concurrent.Future] {
    override def map[A, B](fa: Future[A])(f: (A) => B): Future[B] = fa.map(f)
  }

这样只需要在调用时提供执行上下文。