Francesco
Francesco

Reputation: 66

Implicit ExecutionContext in traits

I would like to have an implicit ExecutionContext passed to a partially implemented trait. In code example:

import scala.concurrent.Future

trait Processor[T,R] {
  def process(op:T): Future[R] = {
    //Do something to get stuff from abstract methods
    Future {
      //Do something that returns type R
    }
  }
}

This will ask for an ExecutionContext, so I have changed the declaration to:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext

trait Processor[T,R] {
  def process(op:T)(implicit executor: ExecutionContext): Future[R] = {
    //Do something to get stuff from abstract methods
    Future {
      //Do something that returns type R
    }
  }
}

But then when I try to extend the trait like this:

import scala.concurrent.ExecutionContext.Implicits.global

class StringProcessor extends Processor[String,String] {
  //Bla bla bla
}

The compiler tells me that the method process is not implemented an my class should be abstract.

How can I ensure that my construct works without having to put an implicit val xc:ExecutionContext in the declaration of the trait?

Upvotes: 4

Views: 2262

Answers (1)

cmbaxter
cmbaxter

Reputation: 35443

I don't seem to be having any issues with the following code, which is similar to your code but provides a full implementation. Not sure what the issue is.

import scala.concurrent.Future
import scala.concurrent.ExecutionContext

trait Processor[T,R] {
  def process(op:T)(implicit executor: ExecutionContext): Future[R] = {
    //Do something to get stuff from abstract methods
    Future {
      getR
    }
  }

  def getR:R
}

class StringProcessor extends Processor[String,String] {
  def getR = "foo"
}

Upvotes: 1

Related Questions