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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.