Junior — Middle
How do the declarations of immutable variables using the val and const val keywords differ in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, the keyword val is used to declare an immutable variable, whose value is assigned at runtime and cannot be changed after initialization. Such variables can be local or class properties.
const val is a compile-time constant. It must be declared at the object, class, or file level, and its value must be known at compile time (for example, literals or expressions evaluated at compile time). const val cannot be used inside functions.
Example:
val runtimeValue = System.currentTimeMillis() // value known only at runtime
const val compileTimeValue = 100 // value known at compile time
Summary:
val— an immutable variable, whose value is set at runtime.const val— an immutable constant, whose value is known at compile time and is used for optimization and constant expressions.