Sobes.tech
Junior

How to create a static variable in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, there is no direct equivalent of the static keyword from Java. Instead, the following are used:

  • companion object: For creating "static" members of a class (fields and methods). They are tied to the class, not to a specific instance.
  • Package-level functions and properties: Declared at the top level of a file (Top-level declarations) and accessible from anywhere without needing to qualify with a class name.

Example with companion object:

class MyClass {
    companion object {
        const val TAG = "MyClass" // Compile-time constant (like final static in Java)
        var instanceCount = 0 // Variable associated with the class
    }

    init {
        instanceCount++
    }
}

Example with package properties:

// In file MyGlobals.kt
const val GLOBAL_CONST = "This is a global constant"
var globalCounter = 0

fun incrementGlobalCounter() {
    globalCounter++
}

Differences and choices:

  • companion object is suitable for members logically related to the class.
  • Package members are convenient for general utilities, constants, or variables not tied to a specific class.
  • For compile-time constants, use const val inside a companion object or as a package declaration.
How to create a static variable in Kotlin? — Android - sobes.tech