Kotlin Companion Objects
In Kotlin, a companion object is an object that is tied to a specific class, rather than being a standalone object like the ones we discussed earlier. A companion object is defined using the companion
keyword followed by the object name, as shown below:
class MyClass { companion object Factory { fun create(): MyClass = MyClass() } }
In this example, we define a companion object called Factory
for the MyClass
class. The companion object has a single function create()
that returns a new instance of the MyClass
class.
Companion objects can access private members of the class they are associated with, just like regular member functions. They can also implement interfaces and inherit from other classes.
Companion objects are often used to provide factory methods for creating instances of a class, or to provide a place for static methods and constants that are closely related to the class. For example:
interface MyInterface { fun doSomething() } class MyClass { companion object : MyInterface { const val NAME = "MyClass" override fun doSomething() { // ... } } }
In this example, we define a companion object that implements the MyInterface
interface and provides a constant NAME
. The companion object also has a function doSomething()
that implements the behavior of MyInterface
. The NAME
constant and the doSomething()
function are both closely related to the MyClass
class and can be accessed using the companion object syntax: MyClass.NAME
and MyClass.doSomething()
.