3
我有以下的代碼塊:爲什麼編譯器無法找到帶Implicits.global的隱式ExecutionContext?
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"
}
}
這裏來進行測試代碼:
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
}
每當我試着運行代碼,我收到以下錯誤:
Cannot find an implicit ExecutionContext.
爲什麼?範圍內已不是scala.concurrent.ExecutionContext.Implicits.global?當此導入直接添加到LocalStorage
對象時,它可以正常工作(!)
但是我失去了改變上下文的可能性。因爲我不想每次都在全局運行此代碼。由於這是akka應用程序的一部分,並且對於「生產」運行時,它應該在某個調度程序上運行。爲了測試,我想在全局執行上下文中運行它。
我錯過了一些重要的概念,或者是我的設計錯了,我失去了這種靈活性?問題在哪裏?
謝謝,我的失明!而已 – jaksky