Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 * 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?

like image 381
Ralph Avatar asked Nov 23 '10 17:11

Ralph


2 Answers

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.

like image 97
Daniel C. Sobral Avatar answered Oct 17 '22 02:10

Daniel C. Sobral


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.

like image 26
axel22 Avatar answered Oct 17 '22 04:10

axel22