Sobes.tech
Junior — Middle

What alternative constructs or keywords that perform the function of static in Java does Kotlin use?

sobes.tech AI

Answer from AI

In Kotlin, there is no keyword static like in Java. Instead, the following constructs are used to create members similar to static:

  • companion object — a companion object inside a class, whose members can be called without creating an instance of the class. Essentially, this is an analog of static methods and fields.
class MyClass {
    companion object {
        const val CONSTANT = 42
        fun staticLikeMethod() = println("Hello from companion object")
    }
}

fun main() {
    println(MyClass.CONSTANT)
    MyClass.staticLikeMethod()
}
  • top-level functions and properties — functions and variables declared outside a class are accessible directly by filename or through import, often replacing static methods.

  • object declaration — declaring an object (singleton) that can contain functions and properties accessible globally.

Thus, companion object is the main way to emulate static in Kotlin.

What alternative constructs or keywords that perform… - sobes.tech