RemcoW
RemcoW

Reputation: 4326

Scope of Traits

I am learning Scala and Akka and I came across an example that confused me. The following code sample was in 1 file.

class RestApi(system: ActorSystem, timeout: Timeout) extends RestRoutes {
  implicit val requestTimeout = timeout
  implicit def executionContext = system.dispatcher

  def createBoxOffice = system.actorOf(BoxOffice.props, BoxOffice.name)
}

trait BoxOfficeApi {
  import BoxOffice._

  def createBoxOffice(): ActorRef

  implicit def executionContext: ExecutionContext
  implicit def requestTimeout: Timeout

  lazy val boxOffice = createBoxOffice()

  // Uninteresting methods here
}

The part that confuses me is the createBoxOffice() call in the BoxOfficeAPI trait. It clearly states that the BoxOfficeAPI has a function which will return an ActorRef. However the implementation for that function is located in the RestApi class which doesn't have any reference to the trait.

How is it possible that the trait can access this method? What is the scope of a trait?

Upvotes: 2

Views: 131

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

How is it possible that the trait can access this method?

I think you're missing the fact that the trait itself has an abstract method called createBoxOffice:

def createBoxOffice(): ActorRef

Which is why it has such a method in scope. It has nothing to do with the declaration of RestApi. Whoever mixes in this trait will have to implement that said method. That means, for example, that if the RestApi class decides to mix in BoxOfficeApi, it already has an implementation available which it will use. For example:

class Baz extends Foo {
  override def quuux(): Unit = println("quuux")
}

trait Foo {
  def quuux(): Unit 
}

Upvotes: 4

Related Questions