can anyone explain the use case for companion obje...
# getting-started
b
can anyone explain the use case for companion objects? static methods/properties in java can be implemented by file private variables or functions instead; I don't really see a good use case for it other than Java interop
s
Namespacing is the only thing that really springs to mind. If it's going to be accessed from outside, I'd rather write
Foo.something
than have a global property called
somethingToDoWithFoo
. Of course companion objects aren't really a great solution to that problem, hence https://youtrack.jetbrains.com/issue/KT-11968. If those proposals end up being implemented I can't see there being much use for companion objects anymore.
b
thank you, that sounds interesting
j
Another important thing is that the
companion object
is an
object
, and as such it can implement interfaces, such as factories. In that sense, the fact that the companion object has the name of the class is interesting.
1
b
You mean for use in reflection?
j
No just for nice API design, without actually needing to use reflection
e
they do have some uses as singleton instances associated with their containing class
kotlinx.serialization.json.Json
, for example, is not meant to be a type directly instantiable by the user, for binary compatibility evolution reasons. the name refers to a builder function for an abstract class, and also that class's companion object which is a default instance
it's the same as a companion object in Scala, except that it's nested in the class instead of being a separate object that happens to use the same name