Companion Objects and Class Members
Explore how Kotlin uses companion objects to define class-level members that are shared across instances. Learn to implement companion objects as singletons within classes, use them for factory methods with private constructors, and understand their role compared to static members.
We'll cover the following...
The classes we created so far had properties and instance methods. If a property or a method is needed at the class level and not on a specific instance of the class, we can’t drop them into the class. Instead, place them in a companion object. In Singleton with Object Declaration, we created singletons. Companion objects are singletons defined within a class—they’re singleton companions of classes. In addition, companion objects may implement interfaces and may extend from base classes, and thus are useful with code reuse as well.
Class-level members
In the next example, a MachineOperator class needs a property and a method at the class level; we achieve that using a companion object:
Within the class, the companion object, literally defined using those keywords, is nested. The property checkedIn within the companion object becomes the class-level property of MachineOperator. Likewise, the method minimumBreak doesn’t belong to any instance; it’s part of the class.
The members of the companion object of a class can be accessed using the class name as reference, like so:
Use caution: placing mutable properties ...