Junior — Middle
How to declare a class property in Kotlin so that it is static?
sobes.tech AI
Answer from AI
In Kotlin, there is no direct equivalent of static properties like in Java. To declare a property that is shared among all instances of a class (static), a companion object is used.
Example:
class MyClass {
companion object {
var staticProperty: String = "Shared property"
}
}
fun main() {
println(MyClass.staticProperty) // Accessing the property without creating an instance
MyClass.staticProperty = "New value"
println(MyClass.staticProperty)
}
Properties and methods inside the companion object are accessible through the class name, which mimics the behavior of static members.