I am creating an asynchronous library using Scala 2.10 futures. The library constructor accepts a sequence of user objects that implement a particular attribute, and then the method in the library class sends some data one at a time to user-defined objects. I want the user to provide an ExecutionContext for asynchronous operations when setting up the main instance, and then for this context so that it is passed to user-defined objects as needed. Simplified (pseudo?) Code:
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] }
You can use something like this:
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") // ... }
I get a compilation error for ThingProcessor :
Cannot find implicit ExecutionContext, either one is required or Import ExecutionContext.Implicits.global
My question is how do I implicitly supply an ExecutionContext that the LibraryObject has user-defined objects ( ThingProcessor and PassThroughProcessor ) or their methods, without making the user (who will write the classes) worry about this - that is, I would prefer that the user does not have to print:
class MyFirstProcessor(implicit context: ExecutionContext)
or
override def process(...)(implicit context: ExecutionContext) = { ... }
source share