2

I have a scala syntax question - say I have a simple dependency pattern construct like the following

trait Master {
  val foobar

  object SubObject extends SubObject {
      foobar = foobar
  }
}

trait SubObject {
  val foobar
}

Obviously, this will not compile, since the reference foobar = foobar is ambiguous.

How do I specify that the RHS of the expression should reference Master's foobar variable? Is there some sort of special usage of 'this' or 'self' that I should know about?

2 Answers 2

6

You can use the Master.this qualifier to specifically reference the outer scope, something like the following:

trait Master {
  val foobar = "Hello world"

  object SubObject extends SubObject {
      val foobar = Master.this.foobar
  }
}

trait SubObject {
  val foobar:String
}
Sign up to request clarification or add additional context in comments.

Comments

5

I believe the easiest way is to use a self-type definition. In addition to a bunch of cool type-theoretic effects, you can use a self-type to create an alias for "this". (Haven't tested this)

trait Master {
  master =>
  val foobar

  object SubObject extends SubObject {
      foobar = master.foobar
  }
}

trait SubObject {
  val foobar
}

3 Comments

Hmm, perhaps not the easiest way, and you should probably give the check-mark to Andrzej's solution, but you should know about the self-type as alias trick as well. Comes in handy in some otherwise tricky edge-cases
I initially started using self types and a simple cake pattern, and I'll likely end up back at that eventually, but I wanted to have a simple Environment object that creates everything for me and doesn't necessarily have to be mixed in to everything that needs it.
Also, I don't necessarily like to use "object" for this sort of dependency injection form (or, indeed, for anything other than companion objects). Slightly less verbose to say something like "lazy val subObject = new SubObject{ foobar = master.foobar}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.