Junior
Rääkige Kotlinis companion objekti kohta.
sobes.tech AI
Vastus AI-lt
companion object in Kotlin is used to define class members (properties and functions) that are shared among all instances of that class, and to access them without creating an instance of the class. It is essentially an equivalent of static members in Java, but implemented as an object inside the class.
Main features:
- Single instance: There can be only 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 has the name
Companion, but it can be explicitly named. - Implementing interfaces: 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.