Scala: Can't get outer class members from inner class reference

半世苍凉 提交于 2019-12-07 21:35:44

问题


I can't seem to get the outer class members from an inner class reference:

class Outer(st: Int)
{
  val valOut = st
  def f = 4
  class Inner { val x = 5 }
}

object myObj {
val myOut = new Outer(8)
val myIn = new myOut.Inner
val myVal: Int = myIn.valOut//value f is not a member of ... myOut.Inner
val x = myIn.f//value valOut is not a member of ... myOut.Inner
}

I've tried this inside packages and in the eclipse worksheet neither works. I'm using Scala 2.10.0RC1 in eclipse 3.7.2 with Scala plug-in 2.1.0M2


回答1:


I don't know why you expect this to compile. After all, Inner does not have those members, only its enclosing class has them. You can achieve what you want this way:

class Outer(st: Int) {
  val valOut = st
  def f = 4
  class Inner {
    val outer = Outer.this
    val x = 5
  }
}

object myObj {
  val myOut = new Outer(8)
  val myIn = new myOut.Inner
  val myVal: Int = myIn.outer.valOut
  val x = myIn.outer.f
}


来源:https://stackoverflow.com/questions/13047083/scala-cant-get-outer-class-members-from-inner-class-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!