Search⌘ K
AI Features

Companion Objects and Class Members

Explore how Kotlin uses companion objects to define class-level members that are shared across instances. Learn to implement companion objects as singletons within classes, use them for factory methods with private constructors, and understand their role compared to static members.

The classes we created so far had properties and instance methods. If a property or a method is needed at the class level and not on a specific instance of the class, we can’t drop them into the class. Instead, place them in a companion object. In Singleton with Object Declaration, we created singletons. Companion objects are singletons defined within a class—they’re singleton companions of classes. In addition, companion objects may implement interfaces and may extend from base classes, and thus are useful with code reuse as well. ...