views:

105

answers:

3

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
}
+7  A: 

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
+3  A: 

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

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

Randall Schulz
Sorry, you were 53 seconds late :-)
lindelof
I know, dammit! That Daniel character is going to be the death of me.
Randall Schulz
+2  A: 

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

object Foo {
  private def bar = 4
}

class Foo {
  def foo = Foo.bar
}
Alexey Romanov
If desired, you can restrict access with `private[this]` def bar = 4`.
retronym