Sobes.tech
Middle

How to create a static field, method, or class in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, there is no native concept of static. Instead, the following are used:

  • companion object: For creating static fields and methods associated with a class but not with a specific instance.
  • Top-level declarations: For creating static fields and methods not tied to any class.
  • object: For creating singleton objects that behave like static classes with fields and methods.

Examples:

Companion object:

class MyClass {
    companion object {
        const val MY_CONSTANT = "Hello" // Static field (compile-time constant)
        var myVariable = 0 // Static field

        fun myStaticMethod() { // Static method
            println("This is a static method.")
        }
    }
}

Access: MyClass.MY_CONSTANT, MyClass.myVariable, MyClass.myStaticMethod().

Top-level declarations:

// MyFile.kt
const val TOP_LEVEL_CONSTANT = "World" // Static field (constant)
var topLevelVariable = 1 // Static field

fun topLevelMethod() { // Static method
    println("This is a top-level method.")
}

Access: TOP_LEVEL_CONSTANT, topLevelVariable, topLevelMethod() (imported from the file).

Object (Singleton):

object MySingleton {
    const val SINGLETON_CONSTANT = "Singleton" // Static field (constant)
    var singletonVariable = 2 // Static field

    fun singletonMethod() { // Static method
        println("This is a singleton method.")
    }
}

Access: MySingleton.SINGLETON_CONSTANT, MySingleton.singletonVariable, MySingleton.singletonMethod(). MySingleton itself behaves like a static class.