🐦 Kotlin Beginner

What is a companion object in Kotlin?

Answer

A companion object is a singleton object declared inside a class. Its members can be accessed using the class name, similar to static members in Java. class MyClass { companion object { fun create() = MyClass() } } — called as MyClass.create(). Companion objects can implement interfaces and have a name (optional). Unlike Java static members, companion object methods are real instance methods of the singleton. Use the @JvmStatic annotation on companion members to generate actual static methods for Java interoperability.