Junior — Middle
How to declare a static method in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, there is no static keyword like in Java. To declare a static method, a companion object is usually used. Methods inside a companion object can be called without creating an instance of the class.
Example:
class MyClass {
companion object {
fun staticMethod() {
println("This is a static method")
}
}
}
fun main() {
MyClass.staticMethod() // call to static method
}
You can also use @JvmStatic for better Java integration, so that the method appears as static on the Java side.