Junior
What is an object and a companion object in Kotlin?
sobes.tech AI
Answer from AI
An object in Kotlin is a way to create a singleton. It is declared using the object keyword and is the only instance of the class, initialized upon first access.
object Singleton {
fun doSomething() {
// Singleton logic
}
}
A companion object is tied to a class and is used to declare static elements (fields and methods) accessible by the class name. Only one companion object can exist per class. It is initialized when the class is loaded.
class MyClass {
companion object {
const val CONSTANT = 123 // Static constant
fun staticMethod() { // Static method
// Static method logic
}
}
}
// Using static elements
val constantValue = MyClass.CONSTANT
MyClass.staticMethod()
Comparison:
| Property | Object (object) | Companion object |
|---|---|---|
| Purpose | Singleton (single instance) | Static elements of the class (fields, methods) |
| Access | By object name | By class name |
| Number per class | Not tied to the class (can be standalone) | One per class |
| Initialization | On first access to the object | When the class is loaded |