scalamonad-transformersscalaz7

Missing Functor and Monad instances when using scala.concurrent.Future with EitherT


I'm trying to use Scalaz EitherT with a scala.concurrent.Future. When trying to use it in a for-comprehension:

import scalaz._
import Scalaz._

val et1:EitherT[Future, String, Int] = EitherT(Future.successful(1.right))

val et2:EitherT[Future, String, String] = EitherT(Future.successful("done".right))

val r:EitherT[Future, String, String] = for {
    a <- et1
    b <- et2
} yield (s"$a $b")

I get the following missing Functor and Monad instances error:

could not find implicit value for parameter F: scalaz.Functor[scala.concurrent.Future]
b <- et2
  ^
could not find implicit value for parameter F: scalaz.Monad[scala.concurrent.Future]
a <- et1

Does scalaz define instances for Functor and Monad for Future? If not are there any other libraries that provide these instances or do I need to write them?


Solution

  • You need an implicit ExecutionContext in scope. import ExecutionContext.Implicits.global will get you the global execution context.

    Full example:

      import scala.concurrent.ExecutionContext.Implicits.global
    
      import scalaz._
      import Scalaz._
    
      val et1:EitherT[Future, String, Int] = EitherT(Future.successful(1.right))
    
      val et2:EitherT[Future, String, String] = EitherT(Future.successful("done".right))
    
      val r:EitherT[Future, String, String] = for {
        a <- et1
        b <- et2
      } yield s"$a $b"
    
      val foo = Await.result(r.run, 1 seconds)
      // => \/-("1 done")