Sobes.tech
Middle

How to create static fields, methods, and classes in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, there is no direct concept of "static" as in Java. To achieve similar functionality, the following mechanisms are used:

  1. Companion objects: Used to create static fields (properties) and methods associated with the class, not its instances.

    class MyClass {
        companion object {
            const val TAG = "MyClass" // Static field
            fun create(): MyClass { // Static method
                return MyClass()
            }
        }
    }
    
  2. Package-level functions and properties: Functions and properties declared directly in a .kt file, outside any class. They can be accessed directly by name.

    // MyFile.kt
    const val GLOBAL_CONSTANT = 123 // Static field at package level
    
    fun globalFunction() { // Static method at package level
        // ...
    }
    
  3. Object declarations: Declare a singleton. All its members (properties and functions) are essentially static.

    object MySingleton {
        const val NAME = "Singleton" // Static field
        fun doSomething() { // Static method
            // ...
        }
    }
    
  4. For "static" nested classes: In Kotlin, nested classes do not have an implicit reference to the outer class by default. This is similar to static class in Java.

    class OuterClass {
        class NestedClass { // Nested class, essentially static
            fun printMessage() {
                println("Hello from nested class")
            }
        }
    }