Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 655
lindelof Avatar asked Aug 19 '10 21:08

lindelof


People also ask

Is companion object singleton in Scala?

In scala, when you have a class with same name as singleton object, it is called companion class and the singleton object is called companion object. The companion class and its companion object both must be defined in the same source file.

What is the advantage of companion object in Scala?

Advantages of Companion Objects in Scala Companion objects provide a clear separation between static and non-static methods in a class because everything that is located inside a companion object is not a part of the class's runtime objects but is available from a static context and vice versa.

What is the easiest way to implement singleton in Scala?

In Scala, a singleton object can extend class and traits. In Scala, a main method is always present in singleton object. The method in the singleton object is accessed with the name of the object(just like calling static method in Java), so there is no need to create an object to access this method.

What is the use of companion object?

companion object is how you define static variables/methods in Kotlin. You are not supposed to create a new instance of Retrofit / ApiService each time you execute a request, however.


3 Answers

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.

like image 199
Daniel C. Sobral Avatar answered Sep 20 '22 00:09

Daniel C. Sobral


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

object Foo {
  private def bar = 4
}

class Foo {
  def foo = Foo.bar
}
like image 40
Alexey Romanov Avatar answered Sep 24 '22 00:09

Alexey Romanov


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

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

like image 43
Randall Schulz Avatar answered Sep 20 '22 00:09

Randall Schulz