How is it recommended to create constants in Kotlin? And what\'s the naming convention? I\'ve not found that in the documentation.
companion object {
//1
Like val, variables defined with the const keyword are immutable. The difference here is that const is used for variables that are known at compile-time.
Declaring a variable const is much like using the static keyword in Java.
Let's see how to declare a const variable in Kotlin:
const val COMMUNITY_NAME = "wiki"
And the analogous code written in Java would be:
final static String COMMUNITY_NAME = "wiki";
Adding to the answers above -
@JvmFieldan be used to instruct the Kotlin compiler not to generate getters/setters for this property and expose it as a field.
@JvmField
val COMMUNITY_NAME: "Wiki"
Static fields
Kotlin properties declared in a named object or a companion object will have static backing fields either in that named object or in the class containing the companion object.
Usually these fields are private but they can be exposed in one of the following ways:
@JvmField annotation;lateinit modifier;const modifier.More details here - https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#instance-fields