0
0
KotlinComparisonBeginner · 3 min read

Const val vs val in Kotlin: Key Differences and Usage

const val is used for compile-time constants and must be a primitive or String known at compile time, while val is for read-only runtime values that can be assigned once but may be computed dynamically. Use const val for fixed constants and val for values initialized at runtime.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of const val and val in Kotlin.

Featureconst valval
Initialization timeCompile-timeRuntime
MutabilityImmutable (constant)Immutable (read-only)
Allowed typesPrimitive types and String onlyAny type
Where allowedTop-level or inside objectsAnywhere (local, class, object)
Use caseFixed constants like PI, URLsValues assigned once but computed or from constructor
MemoryInlined in bytecodeStored as a final field or variable
⚖️

Key Differences

const val is a compile-time constant. This means its value must be known when the code is compiled. It can only hold primitive types like Int, Double, or String. Also, const val can only be declared at the top level or inside an object. The compiler replaces all uses of const val with the actual value, making it very efficient.

On the other hand, val is a read-only variable that is assigned once but can be initialized at runtime. It can hold any type, including complex objects. You can declare val anywhere: inside functions, classes, or objects. Its value is not inlined but stored as a final field or variable.

In summary, use const val for fixed values known at compile time, and use val for values that are assigned once but may depend on runtime information.

⚖️

Code Comparison

Example using const val for a fixed constant:

kotlin
object Constants {
    const val PI = 3.14159
}

fun main() {
    println("Value of PI: ${Constants.PI}")
}
Output
Value of PI: 3.14159
↔️

val Equivalent

Example using val for a read-only value assigned at runtime:

kotlin
class Circle(val radius: Double) {
    val area = 3.14159 * radius * radius
}

fun main() {
    val circle = Circle(2.0)
    println("Area: ${circle.area}")
}
Output
Area: 12.56636
🎯

When to Use Which

Choose const val when you have a value that is truly constant and known at compile time, such as mathematical constants, fixed URLs, or configuration keys. This makes your code faster and clearer.

Choose val when the value is assigned once but depends on runtime information, like user input, constructor parameters, or computed results. It offers flexibility while ensuring immutability after assignment.

Key Takeaways

const val is for compile-time constants and must be primitive or String.
val is a read-only runtime value that can hold any type.
const val can only be declared at top-level or inside objects.
Use const val for fixed constants and val for runtime-assigned values.
const val values are inlined by the compiler, improving performance.