Careeroza
Constants with const
const val
const val is a compile-time constant: the value is known when compiling and is copied into the code wherever it is used. Rules:
- Only at the top level of a file or inside an
object/companion object. - Only for
Stringand primitive types (Int,Double,Boolean...). - The value must be a literal or a constant expression (no function calls).
- By convention constant names are
UPPER_SNAKE_CASE.
Example
App-wide constants such as limits, keys and URLs are good candidates.
const val MAX_LOGIN_ATTEMPTS = 3
const val BASE_URL = "https://api.example.com/v1"
const val GST_PERCENT = 5
fun main() {
println("Max attempts: $MAX_LOGIN_ATTEMPTS")
println("Calling $BASE_URL/orders")
val bill = 400
println("GST: ${bill * GST_PERCENT / 100}")
}Output
Max attempts: 3 Calling https://api.example.com/v1/orders GST: 20
val vs const val
val | const val | |
|---|---|---|
| When the value is known | at run time | at compile time |
| Can call a function | yes: val now = System.currentTimeMillis() | no |
| Where allowed | anywhere | top level or in an object |
| Types | any | String and primitives only |
| Java equivalent | final variable | static final constant |