Additional Resources
Answer
Both const val and val are used to declare immutable (read-only) properties in Kotlin, but they differ in when and how their values are determined.
const val - Compile-Time Constants
const val declares compile-time constants whose values must be known during compilation.
Requirements:
- Value is inlined into bytecode at compile-time for better performance
const val API_URL = "https://api.example.com" // Valid
const val MAX_RETRY = 3 // Valid
const val TIME = System.currentTimeMillis() // Invalid - function call
val - Runtime Constants
val declares runtime constants that are initialized when the code executes.
Characteristics:
val currentTime = System.currentTimeMillis() // Valid - runtime initialization
val userName = getCurrentUser() // Valid - function call
val config: String
get() = if (isDev) "dev" else "prod" // Valid - custom getter
When to Use Which?
Use const val for:
Use val for:
Key Difference
The main distinction is timing: const val is evaluated at compile-time and inlined for performance, while val is evaluated at runtime and stored in memory.