开发者

Scala variable scoping question

I have a scala syntax question - say I h开发者_如何学运维ave 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?


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
}


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜