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:
-
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() } } } -
Package-level functions and properties: Functions and properties declared directly in a
.ktfile, 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 // ... } -
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 // ... } } -
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 classin Java.class OuterClass { class NestedClass { // Nested class, essentially static fun printMessage() { println("Hello from nested class") } } }