Junior — Middle
Is the companion object shared among all instances of the class?
sobes.tech AI
Answer from AI
Yes, a companion object in Kotlin is shared among all instances of a class. It is a kind of singleton associated with the class itself, not with any specific instance.
A companion object allows you to define functions and properties that can be called without creating an instance of the class, similar to static methods and fields in Java.
Example:
class MyClass {
companion object {
val sharedValue = 42
fun printValue() {
println("Shared value: $sharedValue")
}
}
}
fun main() {
println(MyClass.sharedValue) // 42
MyClass.printValue() // Shared value: 42
}
Here, sharedValue and printValue are shared among all instances of MyClass.