Why can't the compiler find the implicit ExecutionContext with Implicits.global imported?

I have the following piece of code:

import java.util.concurrent.Executor
import scala.concurrent.Future

trait Storage {
  def store(location: String, content: Array[Byte])(implicit exec: Executor): Future[String]
}
object LocalStorage extends Storage {

override def store(location: String, content: Array[Byte])(implicit exec: Executor): Future[String] =
  Future {
    ... do some stuff ...
    "Hello"
  }
}

      

And here is the code to test:

object LocalStorageTest extends App{
  import scala.concurrent.ExecutionContext.Implicits.global

  val testImage = AsyncWebClient get "some url"
  val result = testImage.flatMap{content => LocalStorage.store("logo.png",content)}
  val status =Await.result(result, 30 seconds)
  println(status)
  AsyncWebClient.shutDown
}

      

Whenever I try to run the code, I get the following error:

Cannot find implicit ExecutionContext.

Why? Is scala.concurrent.ExecutionContext.Implicits.global in scope already? When this import is added directly to the object LocalStorage

, it works (!)

BUT I am losing the ability to change the context. As I don't want to run this code on global every time. Since this is part of the akka application, and for the "production" runtime, it is supposed to run on some kind of dispatcher. Just for testing purposes, I would like to run it in a global execution context.

Am I missing an important concept here, or is my design wrong that I am losing this flexibility? Where is the problem?!

+3


source to share


1 answer


An ExecutionContext

is not the same as Executor

. You have to force the method to accept implicit exec: ExecutionContext

( scala.concurrent.ExecutionContext

) and then it will behave as you expect.



+4


source







All Articles