18

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
}
lindelof
  • 34,556
  • 31
  • 99
  • 140

3 Answers3

17

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.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
4

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

object Foo {
  private def bar = 4
}

class Foo {
  def foo = Foo.bar
}
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
3

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

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

Randall Schulz
  • 26,420
  • 4
  • 61
  • 81