Do I need to import members of a singleton object into its companion class in Scala?
The Good Book states that:
A class and its companion object can access each other’s private members.
Perhaps naively, I took this as meaning that a class didn't need to explicitly import t开发者_StackOverflow社区he members from its companion object. I.e., the following would work:
object Foo {
def bar = 4
}
class Foo {
def foo = bar
}
Well, the reason you're reading this is that it doesn't. So do I really need to declare something like this:
class Foo {
import Foo._
def foo = bar
}
Yes, you do, just as you state. There's access, and there's scope -- what companion class/objects have is access, not scope.
It's like declaring something public vs private -- it doesn't bring those members into everyone's scope, just give them access to it.
"Can access private members" means that the following works:
object Foo {
private def bar = 4
}
class Foo {
def foo = Foo.bar
}
Yes (and I want my 15 points for that!)
But to expand, their scopes do not overlap, so the import is necessary.
精彩评论