Junior
Tell me about the companion object in Kotlin.
sobes.tech AI
Answer from AI
companion object in Kotlin is used to define class members (properties and functions) that are shared among all instances of the class, and to access them without creating an instance of the class. Essentially, it is similar to static members in Java, but implemented as an object inside the class.
Main features:
- Single instance: There can only be one
companion objectinside a class. - Initialization: It is initialized when the class is first loaded.
- Access to private members: It has access to the private members of the outer class.
- Naming: By default, it is named
Companion, but it can be explicitly named. - Interface implementation: It can implement interfaces.
Example usage:
class MyClass {
companion object {
const val TAG = "MyClass" // Constant
fun createInstance(): MyClass { // Factory method
return MyClass()
}
}
fun doSomething() {
println("Doing something...")
}
}
fun main() {
println(MyClass.TAG) // Access to companion object member
val instance = MyClass.createInstance() // Using factory method
instance.doSomething()
}
Advantages:
- More semantic: Allows grouping related "static" members in one place.
- Flexibility: Can implement interfaces, which is useful for design patterns.
- Access to private members: Simplifies implementation of factory methods and singletons inside the class.