How is it recommended to create constants in Kotlin?

Technology CommunityCategory: KotlinHow is it recommended to create constants in Kotlin?
VietMX Staff asked 3 years ago

In Kotlin, if you want to create the local constants which are supposed to be used with in the class then you can create it like below:

val MY_CONSTANT_1 = "Constants1"
// or 
const val MY_CONSTANT_2 = "Constants2"

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.

Also avoid using companion objects. Behind the hood, getter and setter instance methods are created for the fields to be accessible. Calling instance methods is technically more expensive than calling static methods. Instead define the constants in object:

object DbConstants {
        const val TABLE_USER_ATTRIBUTE_EMPID = "_id"
        const val TABLE_USER_ATTRIBUTE_DATA = "data"
}