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
class Myclass {
companion object {
const val MYCONSTANT = 479
}
you have two choices you can use const keyword or use the @JvmField which makes it a java's static final constant.
class Myclass {
companion object {
@JvmField val MYCONSTANT = 479
}
If you use the @JvmField annotation then after it compiles the constant gets put in for you the way you would call it in java.
Just like you would call it in java the compiler will replace that for you when you call the companion constant in code.
However, if you use the const keyword then the value of the constant gets inlined. By inline i mean the actual value is used after it compiles.
so to summarize here is what the compiler will do for you :
//so for @JvmField:
Foo var1 = Constants.FOO;
//and for const:
Foo var1 = 479