Companion objects
Kotlin, as opposed to Java, lacks the ability to define static members, but instead it allows us to define objects that are associated with a class. In other words, an object is initialized only once; therefore, only one instance of an object exists, sharing its state across all instances of a particular class. When a singleton object is associated with a class of the same name, it is called the companion object of the class, and the class is called the companion class of the object:
The preceding diagram presents three instances of the Car
class sharing a single instance of an object.
Members, such as methods and properties, defined inside a companion object may be accessed similarly to the way we access static fields and methods in Java. The main purpose of a companion object is to have code that is related to a class, but not necessary to any particular instance of this class. It is a good way to define members that would be defined as static in Java, for example, factory...