...

/

The Companion Objects

The Companion Objects

Explore the role of companion objects in Kotlin, their use cases, and how they replace traditional static elements, enabling inheritance and interfaces.

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 ...