RemcoW RemcoW - 1 year ago 74
Scala Question

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,

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
call in the
trait. It clearly states that the
has a function which will return an
. However the implementation for that function is located in the
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?

Answer Source

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 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download