What is the equivalent of Java static methods in Kotlin?
In Kotlin, you can use the companion object to define static methods and properties.
In Kotlin, you can use the companion object to define methods and properties that are accessed using class-name syntax.
Here is an example of how to define a method in a companion object:
class MyClass {
companion object {
fun staticMethod() {
// method implementation
}
}
}You can call the method using the name of the class:
MyClass.staticMethod()Here is an example of how to define a property in a companion object:
class MyClass {
companion object {
val staticProperty = "static property value"
}
}You can access the property using the name of the class:
val value = MyClass.staticPropertyIn Kotlin, the companion object is a singleton, which means that there is only one instance of the object. Its members are accessed via class-name sugar, but they are technically instance members of the companion object, not JVM static methods by default.
To generate actual JVM static methods for Java interoperability, use the @JvmStatic annotation:
class MyClass {
companion object {
@JvmStatic
fun javaStaticMethod() {
// generates a true JVM static method
}
}
}When compiled, this allows Java code to call MyClass.javaStaticMethod() directly as a standard static method.
I hope this helps. Let me know if you have any questions.