ProgrammingAndroid Developer / Backend Developer

How does the initialization of constant values (const val) and compile-time constants work in Kotlin? What is the difference from a regular val, what are the limitations, how is it used for annotations, and why is it not always possible to use const val where desired?

Pass interviews with Hintsage AI assistant

Answer

In Kotlin, the const val keyword is used to declare compile-time constants, i.e. values that are known and computed at compile time.

  • const val is only available for top-level variables or for properties declared in object objects or companion object.
  • The value must be of types: String, numeric primitives, or Boolean.
  • It is used for annotations and decorators where the value must be substituted at compile time.

val is an immutable variable, but its value can be assigned at runtime, allowing for computations or function calls during initialization:

val timestamp = System.currentTimeMillis() // This is NOT const val const val APP_NAME = "MyApp" // This is a compile-time constant

In annotations, only const val can be used, for example:

const val AUTHOR = "John Doe" @Target(AnnotationTarget.CLASS) annotation class Author(val name: String) @Author(AUTHOR) class Example

If you try to use val in such cases, it will result in a compilation error.


Trick Question

Why can't you declare const val inside a regular class?

Answer: Because const val requires the variable to be available at compile time, while instance variables of a class are initialized only when the object is created, hence they cannot be compile-time constants.

class Example { // Error! Cannot do this // const val CLASS_NAME = "MyClass" }

History

The build broke because a developer tried to pass a computed runtime value through an annotation.

The developer declared:

val version = getVersionFromConfig() @Target(AnnotationTarget.CLASS) annotation class Version(val value: String) @Version(version) class App

The project did not compile, as only const val can be used in annotation arguments!


History

Error on Android: trying to use local variables as constant keys in Intent.

class Keys { companion object { val EXTRA_USER_ID = "userId" } } intent.putExtra(Keys.EXTRA_USER_ID, userId)

In some tools or frameworks, const val is expected rather than a regular val — otherwise, the IDE or Android resources do not recognize these values as compile-time constants.


History

Using an inappropriate type for const val.

const val LIST = listOf(1,2,3) // Error! Only primitives and String are allowed.

Lack of knowledge about type limitations led to a compilation error and wasted time.