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 String and 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

valconst val
When the value is knownat run timeat compile time
Can call a functionyes: val now = System.currentTimeMillis()no
Where allowedanywheretop level or in an object
TypesanyString and primitives only
Java equivalentfinal variablestatic final constant