我正在使用 Scala 2.10 期货创建一个异步库。库的构造函数采用一系列实现特定特征的用户定义对象,然后库类上的方法将一些数据一个接一个地发送到用户定义对象中。我希望用户ExecutionContext
在设置主实例时提供异步操作,然后根据需要将该上下文传递给用户定义的对象。简化(伪?)代码:
case class Response(thing: String)
class LibraryObject(stack: Seq[Processor])(implicit context: ExecutionContext) {
def entryPoint(data: String): Future[Response] = {
val response = Future(Response(""))
stack.foldLeft(response) { (resp, proc) => proc.process(data, resp) }
}
}
trait Processor {
def process(data: String, resp: Future[Response]): Future[Response]
}
它可能会像这样使用:
class ThingProcessor extends Processor {
override def process(data: String, response: Future[Response]) = {
response map { _.copy(thing = "THE THING") }
}
}
class PassThroughProcessor extends Processor {
override def process(request: Request, response: Future[Response]) = {
response
}
}
object TheApp extends App {
import ExecutionContext.Implicits.global
val stack = List(
new ThingProcessor,
new PassThroughProcessor
)
val libObj = new LibraryObject(stack)
val futureResponse = libObj.entryPoint("http://some/url")
// ...
}
我收到以下编译错误ThingProcessor
:
找不到隐式 ExecutionContext,要么自己需要,要么导入
ExecutionContext.Implicits.global
我的问题是,我如何隐式地ExecutionContext
向LibraryObject
用户定义的对象(ThingProcessor
and PassThroughProcessor
)或其方法提供必须的内容,而不会让用户(将编写类)担心它——也就是说,我更喜欢用户不必键入:
class MyFirstProcessor(implicit context: ExecutionContext)
或者
override def process(...)(implicit context: ExecutionContext) = { ... }