Search⌘ K
AI Features

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.

// Java
class User {
// Static element definition
public static User empty() {
return new User();
}
}
// Static element usage
User user = User.empty()
Defining and using a static element in Java

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.

// Kotlin
class User {
object Producer {
fun empty() = User()
}
}
// Usage
val user: User = User.Producer.empty()
Creating a static object using Kotlin’s object declaration

Enhancing

...