Sobes.tech
Junior — Middle

What are the differences between the keywords const val and val in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, the keyword val denotes an immutable variable (read-only), which can be assigned once during initialization, but its value can be computed at runtime.

const val is a compile-time constant, which must be of a primitive type or String and initialized with a value known at compile time. Such constants can be used, for example, in annotations or as parameters requiring constants.

Main differences:

  • const val is always a static constant, accessible at the class level (only in objects or top-levels).
  • val is a regular immutable property, which can be computed dynamically.

Example:

const val MAX_COUNT = 10 // compile-time constant
val currentTime = System.currentTimeMillis() // value computed at runtime