-
What is the intended meaning of “companion object”? Why is it called “companion”?
First, Kotlin doesn’t use the Java concept of
static
members because Kotlin has its own concept ofobject
s for describing properties and functions connected with singleton state, and Javastatic
part of a class can be elegantly expressed in terms of singleton: it’s a singleton object that can be called by the class’ name. Hence the naming: it’s an object that comes with a class.Its name used to be
class object
anddefault object
, but then it got renamed tocompanion object
which is more clear and is also consistent with Scala companion objects.Apart from naming, it is more powerful than Java
static
members: it can extend classes and interfaces, and you can reference and pass it around just like other objects. -
Does it mean that to create multiple static properties, I have to group it together inside
companion object
block?Yes, that’s the idiomatic way. Or you can even group them in non-companion objects by their meaning:
class MyClass { object IO { fun makeSomethingWithIO() { /* ... */ } } object Factory { fun createSomething() { /* ... */ } } }
-
To instantly create a singleton instance that is scoped to a class, I often write
/*...*/
which seems like an unidiomatic way of doing it. What’s the better way?It depends on what you need in each particular case. Your code suits well for storing state bound to a class which is initialized upon the first call to it.
If you don’t need it to be connected with a class, just use object declaration:
object Foo { val something by lazy { ... } }
You can also remove
lazy { ... }
delegation to make the property initialize on first class’ usage, just like Java static initializersYou might also find useful ways of initializing singleton state.