18
votes

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 the 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
}
3

3 Answers

17
votes

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.

4
votes

"Can access private members" means that the following works:

object Foo {
  private def bar = 4
}

class Foo {
  def foo = Foo.bar
}
3
votes

Yes (and I want my 15 points for that!)

But to expand, their scopes do not overlap, so the import is necessary.