jaksky
jaksky

Reputation: 3405

Why can't the compiler find 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 comes the code for testing:

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 am getting the following error:

Cannot find an implicit ExecutionContext.

Why? Isn't scala.concurrent.ExecutionContext.Implicits.global in scope already? When this import is added directly to LocalStorage object, it works (!)

BUT I am loosing a possibility to alter the context. Since I do not want to run this code on global every time. As this is a part of an akka application and for "production" runtime it is supposed to run on some dispatcher. Just for testing I would like to run it on a global execution context.

Am I missing some important concept here or is my design wrong that I am loosing such flexibility? Where is the issue?!

Upvotes: 3

Views: 2799

Answers (1)

lmm
lmm

Reputation: 17431

An ExecutionContext is not the same thing as an Executor. You should make the method accept an implicit exec: ExecutionContext (scala.concurrent.ExecutionContext) and then it will behave as you expect.

Upvotes: 4

Related Questions