How is it recommended to create constants in Kotlin?
How is it recommended to create constants in Kotlin?
Here are a few recommended ways to create constants in Kotlin:
const
keywordFor primitive types and String, you can use the const
keyword to define compile-time constants. These constants must be top-level or inside an object declaration.
const val PI = 3.14159
const val TAG = "MyApp"
object
declarationsYou can define constants inside an object
declaration, which creates a singleton object.
object Constants {
const val PI = 3.14159
const val TAG = "MyApp"
}
To access these constants, use Constants.PI
or Constants.TAG
.
companion object
Inside a class, you can define constants in a companion object
. This is useful when the constants are related to the class.
class MyCl...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào