Junior — Middle
What is the purpose of the companion object in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, the companion object is used to declare a companion object inside a class. This allows creating static members (methods and properties) that belong to the class rather than a specific instance.
A companion object behaves like a singleton associated with the class, and its members can be accessed through the class name without creating an object.
Example:
class MyClass {
companion object {
fun create(): MyClass = MyClass()
const val CONSTANT = 42
}
}
fun main() {
val instance = MyClass.create() // calling the companion method
println(MyClass.CONSTANT) // accessing the companion constant
}
Thus, companion object replaces static members, which are not present in Kotlin, and allows conveniently grouping class-related functions and data.