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.
| Feature | const val | val |
|---|---|---|
| Initialization time | Compile-time | Runtime |
| Mutability | Immutable (constant) | Immutable (read-only) |
| Allowed types | Primitive types and String only | Any type |
| Where allowed | Top-level or inside objects | Anywhere (local, class, object) |
| Use case | Fixed constants like PI, URLs | Values assigned once but computed or from constructor |
| Memory | Inlined in bytecode | Stored 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:
object Constants {
const val PI = 3.14159
}
fun main() {
println("Value of PI: ${Constants.PI}")
}val Equivalent
Example using val for a read-only value assigned at runtime:
class Circle(val radius: Double) { val area = 3.14159 * radius * radius } fun main() { val circle = Circle(2.0) println("Area: ${circle.area}") }
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.const val for fixed constants and val for runtime-assigned values.const val values are inlined by the compiler, improving performance.