Static Fields in Kotlin

There is no static keyword in the Kotlin language, so what do you do when you want a static field or constant in Kotlin?

Static Fields in Kotlin

In Java, when declaring a constant, you use something like the following:

public static final String NAME = "kotlintips.com";

In Kotlin, there’s no static keyword, so what’s the equivalent?

Kotlin defines the concept of Compile Time Constants. These can be expressed like this:

class Message {
    companion object {
        const val GOODBYE = "Goodbye"
    }
}

This can be used like this:

fun main() {
    println(Message.GOODBYE)
}

To define a static final property (ie. a field with getter), you can use the following:

class Message {
    companion object {
        @JvmStatic val GOODBYE = "Goodbye"
    }
}

And to conclude, by using the JvmField annotation, you can define a static final field:

class Hello {
    companion object {
        @JvmField val GOODBYE = "Goodbye"
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *