07-20-2023, 09:03 AM
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:
- Why is it called "companion"?
- Does it mean that to create multiple _static_ properties, I have to group it together inside `companion object` block?
- To instantly create a singleton instance that is scoped to a class, I often write
:
companion object {
val singleton by lazy { ... }
}
which seems like an unidiomatic way of doing it. What's the better way?
I am confused with:
- Why is it called "companion"?
- Does it mean that to create multiple _static_ properties, I have to group it together inside `companion object` block?
- To instantly create a singleton instance that is scoped to a class, I often write
:
companion object {
val singleton by lazy { ... }
}
which seems like an unidiomatic way of doing it. What's the better way?