https://kotlinlang.org logo
#getting-started
Title
# getting-started
b

Bernhard

03/18/2024, 11:29 AM
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

Sam

03/18/2024, 11:37 AM
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

Bernhard

03/18/2024, 11:41 AM
thank you, that sounds interesting
j

Joffrey

03/18/2024, 2:34 PM
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

Bernhard

03/18/2024, 2:35 PM
You mean for use in reflection?
j

Joffrey

03/18/2024, 2:35 PM
No just for nice API design, without actually needing to use reflection
e

ephemient

03/18/2024, 2:41 PM
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