开发者

Scala protected object

In Scala, if I create an object and companion class, identifiers declared with the protected modifier can be accessed from the class if the object is imported:

object Foo {
  protected val X = 42
}
class Foo {
  import Foo._
  def getX(): Int = X
}

However, the protected identifier cannot be accessed from a subclass of the class Foo:

class Bar extends Foo {
  import Foo._
  def getX(): Int = X *开发者_如何学JAVA 2
}

I get a compile-time error in Bar.

Other then (implied) public, is there any access modifier I can place on X so that it can be accessed from subclasses of its companion, but not from other classes, including other classes in the same package?


That's because only the class Foo is companion to the object Foo.

Here, the difference between private and protected meaningless, since the object Foo is a singleton, which means there isn't any other object that has the same class as object Foo (Foo.type).

Access restriction in Scala is package-based, so the short answer is no. You could make a forwarder on the base class, though, unless you need it to be available without an instance.

In your place, however, I'd go back to the design board.


In such cases, I would suggest using a package private modifier, like below:

object Foo {
  private[your_package] val X = 42
}

The value will still be visible to everybody else in the package.


To achieve the same thing, One solution to this problem can be:

class Bar extends Foo {
  import Foo._
  override def getX(): Int = super.getX * 2
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜