Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A read-only variable in Kotlin is declared using the val (value) keyword and represents a reference that can be assigned exactly once. Once initialized, the variable’s reference is locked, and any subsequent attempt to reassign it will result in a compilation error.
val language: String = "Kotlin"
// language = "Java" // Compilation error: Val cannot be reassigned

Type Inference

If the variable is initialized at the point of declaration, the Kotlin compiler infers the type, making the explicit type declaration optional.
val version = 1.9 // Type inferred as Double

Deferred Initialization

Immediate assignment is not strictly required. A read-only variable can be declared without an initial value, provided the compiler can statically verify that it is initialized exactly once across all possible execution paths before its first read.
val status: Int
val condition = true

if (condition) {
    status = 200
} else {
    status = 404
}
// status is guaranteed to be initialized exactly once before being accessed

Read-Only vs. Immutability

The val keyword enforces a read-only reference, not deep object immutability. If a val holds a reference to a mutable object, the reference itself cannot be changed to point to a new object in memory, but the internal state of the referenced object can still be mutated.
val items = mutableListOf("A", "B")
items.add("C") // Valid: Mutating the internal state of the referenced object
// items = mutableListOf("D") // Invalid: Attempting to reassign the reference

Properties and Custom Getters

When declared as a class-level or interface-level property, val instructs the compiler to generate a getter method but no setter method. Because a val property can utilize a custom getter, its returned value is not guaranteed to be constant across multiple invocations. It lacks a backing field if a custom getter is provided without referencing field.
class SystemInfo {
    val timestamp: Long
        get() = System.currentTimeMillis() // Returns a different value on each access
}
In this scenario, timestamp is read-only (it cannot be assigned a value via a setter), but its evaluated result is dynamic, demonstrating that val dictates assignment restrictions rather than strict state immutability.
Master Kotlin with Deep Grasping Methodology!Learn More