What is the intended meaning of "companion object"? So far I have been using it just to replace Java's static
when I need it.
I am confused with:
companion object
block?:
companion object {
val singleton by lazy { ... }
}
which seems like an unidiomatic way of doing it. What's the better way?
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 of object
s for describing properties and functions connected with singleton state, and Java static
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
and default object
, but then it got renamed to companion 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 initializers
You might also find useful ways of initializing singleton state.