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 declares compile-time constants whose values must be known during compilation.
Requirements:
const val API_URL = "https://api.example.com" // Valid
const val MAX_RETRY = 3 // Valid
const val TIME = System.currentTimeMillis() // Invalid - function call
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
Use const val for:
Use val for:
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.
Mark this when you can explain the answer in your own words.
Help fellow developers prepare for interviews
Sharing helps the Android community grow ๐