When should we use a companion object?

You may be wondering when you may want to use a companion object. A few examples of when to use a companion object include the following:

  • Writing factory methods for classes with private constructors
  • Providing static constants and methods
  • Scoping top-level properties and functions

Companion objects have access to the private properties, methods, and constructors of the enclosing class. This means that if a class has a private constructor, its companion object can still instantiate instances of the enclosing class. This allows you to write factory methods on a companion object to control how a class is created.

While Kotlin generally prefers top-level functions and properties, it's possible to leverage ...

Get Mastering Kotlin now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.