0 votes
in Kotlin by
How is it recommended to create constants in Kotlin?

1 Answer

0 votes
by
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"

}

Related questions

0 votes
asked Oct 5, 2021 in Kotlin by rajeshsharma
0 votes
asked May 26, 2022 in Kotlin by Robin
...