synapse
synapse

Reputation: 5728

Scalaz and scala.concurrent.Future

OptionT[Future[_], A] transformer needs implicit Functor[Future] in scope. But if evidence is moved to another file that doesn't have implicit ExecutionContext the compiler fails with error Cannot find an implicit ExecutionContext.. Is it possible to write a code that wouldn't have evidence definitions all over the place and will use ExecutionContext that's available at invocation of 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)
  }
}

Upvotes: 1

Views: 220

Answers (1)

Alvaro Carrasco
Alvaro Carrasco

Reputation: 6172

Have the evidence require the execution context:

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)
  }

This way the execution context need only be provided at invocation.

Upvotes: 2

Related Questions