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
}
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.
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.
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.
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.
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.
"Can access private members" means that the following works:
object Foo {
private def bar = 4
}
class Foo {
def foo = Foo.bar
}
Yes (and I want my 15 points for that!)
But to expand, their scopes do not overlap, so the import is necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With