0

How can I make a field visible for subclasses, but not visible for their inner classes?

class Foo

class Parent {
  protected val x = 5
} 

class Sub extends Parent {
  println(x) // 5

  new Foo {
    println(x) // it's 5, but I want it to be a compiler error...
  }
}
  • 2
    I don't think this is possible. Lexical nesting is kind of an important thing in Scala. But hey, there's lots of things you can do, maybe someone will surprise me. – Jörg W Mittag Sep 22 '16 at 21:11
  • 2
    It might also be important to recognize that new Foo doesn't refer to an Inner Class because it is merely instantiated within Sub - it is not defined there. Because of that, the x in Sub's new Foo is actually not Foo having access to Parent's x. It is Sub accessing Parent's x while he is instantiating a new Foo. I hope that makes some sense. Note that you cannot define Foo as class Foo{ def y = x } because x is not available. – Idan Waisman Sep 22 '16 at 21:30

0 Answers0