The Companion Objects
Explore how Kotlin replaces static elements with companion objects, allowing implicit method calls on classes and supporting inheritance in these objects. Understand the concept through examples involving currency classes and discover how companion objects enhance code organization and functionality.
Introduction
Kotlin has addressed the problem of introducing inheritance for static elements by introducing companion objects. However, to make that possible, it first needed to eliminate actual static elements, i.e., elements that are called on classes, not objects.
// Javaclass User {// Static element definitionpublic static User empty() {return new User();}}// Static element usageUser user = User.empty()
Kotlin’s approach
We don’t have static elements in Kotlin, but we don’t need them because we use object declarations instead. If we define an object declaration in a class, it is static by default (just like classes defined inside classes), so we can directly call its elements.
// Kotlinclass User {object Producer {fun empty() = User()}}// Usageval user: User = User.Producer.empty()