...

/

Companion Objects and Class Members

Companion Objects and Class Members

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:

Press + to interact
class MachineOperator(val name: String) {
fun checkin() = checkedIn++
fun checkout() = checkedIn--
companion object {
var checkedIn = 0
fun minimumBreak() = "15 minutes every 2 hours"
}
}

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:

Press + to interact
MachineOperator("Mater").checkin()
println(MachineOperator.minimumBreak()) //15 minutes every 2 hours
println(MachineOperator.checkedIn) //1

Use caution: placing mutable properties ...