Skip to main content
A const property in Kotlin is a compile-time constant, meaning its value is resolved and directly inlined into the calling code during compilation. Unlike a standard read-only val property—which is evaluated at runtime and typically accessed via a generated getter method—a const val replaces all property references with the literal value in the generated JVM bytecode. Because their values are strictly guaranteed at compile time, const properties possess the unique capability of being used as arguments in annotations (e.g., @Deprecated(MESSAGE)), a context where standard val properties are strictly prohibited.

Declaration Requirements

To declare a compile-time constant, the property must be prefixed with the const val modifiers. The Kotlin compiler enforces strict structural and typing rules for const properties:
  1. Placement: It must be declared at the top level of a file, as a member of an object declaration, or within a companion object. It cannot be a standard class property or a local variable.
  2. Type Restriction: The property type must be a String or a primitive type (Int, Long, Double, Float, Boolean, Char, Byte, Short).
  3. Initialization: It must be initialized immediately with a literal value or another compile-time constant. It cannot be initialized by a function call that requires runtime execution.
  4. No Custom Getters: It cannot have a custom getter implementation, as the value must be statically determinable at compile time.

Syntax

Compilation Behavior and Bytecode

Understanding the distinction between val and const val requires examining the generated Java bytecode and compiler optimizations. Standard val:
The compiler generates a private final backing field and a getter method (getRuntimeConstant()). Accessing this property incurs the overhead of a method invocation at runtime. Compile-time const val:
The compiler generates a static final field that strictly respects the declared Kotlin visibility modifiers. A private const val generates a private static final field, while a public one generates a public static final field. More importantly, wherever COMPILE_CONSTANT is referenced, the compiler performs constant propagation and constant folding. If you write:
The Kotlin compiler evaluates constant expressions at compile time. The generated bytecode directly assigns the pre-computed value, completely eliminating both the property reference and the addition operation from the compiled output:
This strips the call site of method dispatch overhead and allows the JVM to perform further static optimizations.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More