lindelof
lindelof

Reputation: 35240

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

Upvotes: 19

Views: 1694

Answers (3)

Alexey Romanov
Alexey Romanov

Reputation: 170723

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

object Foo {
  private def bar = 4
}

class Foo {
  def foo = Foo.bar
}

Upvotes: 5

Randall Schulz
Randall Schulz

Reputation: 26486

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

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

Upvotes: 3

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297165

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.

Upvotes: 17

Related Questions