Kotlin Companion
The Kotlin Companion keyword is used to indicate that a particular class has a companion object. A companion object is an object that is defined inside a class and has the same name as the class, but with a companion keyword in front of it.
Companion objects are used for several purposes, such as:
- They can contain factory methods for creating instances of the class.
- They can provide a singleton instance of the class.
- They can contain additional utility methods related to the class.
Here is an example of a class with a companion object:
class MyClass {
companion object {
fun create(): MyClass {
// factory method
return MyClass()
}
}
}
val myObject = MyClass.create()