Junior — Middle
What is the purpose of declaring with the keywords 'const' and 'val' in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, the keywords const and val are used to declare immutable values, but with different characteristics:
-
constare compile-time constants. They must be primitive types or strings and are declared at the object or file level. The value ofconstcannot be changed and is known at compile time. -
valare runtime immutable variables. The value is assigned once during initialization and cannot be changed, but it can be computed at runtime.
Example:
const val MAX_COUNT = 100 // compile-time constant
val currentTime = System.currentTimeMillis() // immutable runtime value