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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With