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:

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 companion objects to scope those properties and functions to an enclosing class. This can help avoid pollution of the global namespace.