Introduction

One of the best aspects of Kotlin is how well-designed the entire language is. From the moment the first stable version arrived in 2016 until now, Kotlin has continuously improved, making it easy for developers to create top Android experiences. One neat, sometimes overlooked feature of Kotlin is a companion object. Kotlin companion objects are accessible, intuitive ways to accomplish fairly routine tasks when writing an Android app.

What Are Kotlin Companion Objects?

Kotlin companion objects are objects associated with or “living inside” a class. A class is a collection of methods and data structures, so a companion object is merely a data structure living within a class.

Companion objects have specific, unique properties that make them remarkably beneficial:

  1. Every companion object is a single instance. It acts as a singleton within the class, no matter how many instances of the class exist. When you call Class.companionObjectMethod, you access the single instance of companionObject. In this respect, a companion object behaves like a static method or class.

  2. The parent class fully encapsulates the object, hence its name. The singleton object you declare doesn’t live in a global scope but rather lives “within” the class namespace.

  3. These objects aren’t merely static methods. They can implement interfaces and inherit from other classes. They can also access private members of their enclosing class. These objects are actual Kotlin objects; they merely associate with a class that encompasses them.

See forum comments
Download course materials from Github
Previous: Quiz: Write Extensions Next: Instruction