Interview frequency: …
Short answer
const val is a value known at compile time (compile-time constant) for primitive types and strings only, while val is assigned at runtime.
Explanation
const val must be declared at the top level of a file or inside an object/companion object, and its value is predetermined and inlined directly into the bytecode at every use with no get call. A regular val can receive the result of a function computed at runtime such as System.currentTimeMillis().
Code example
const val TIMEOUT_SECONDS = 30 // Compile-time constant
// const val CURRENT_TIME = System.currentTimeMillis() // Error: not allowed
val currentTime = System.currentTimeMillis() // Allowed: Runtime evaluationCommon mistakes
- Trying to use const val with custom objects that are not primitive types or String.
- Declaring const val as a local variable inside a function or directly inside a regular class.