What is the equivalent of Java static final fields in Kotlin?

pdeva :

In Java, to declare a constant, you do something like:

class Hello  {
 public static final int MAX_LEN = 20;
}

What is the equivalent in Kotlin?

Ruslan :

According Kotlin documentation this is equivalent:

class Hello {
    companion object {
        const val MAX_LEN = 20
    }
}

Usage:

fun main(srgs: Array<String>) {
    println(Hello.MAX_LEN)
}

Also this is static final property (field with getter):

class Hello {
    companion object {
        @JvmStatic val MAX_LEN = 20
    }
}

And finally this is static final field:

class Hello {
    companion object {
        @JvmField val MAX_LEN = 20
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=419128&siteId=1