Concept Flow - Val for immutable references
Declare val x = 10
x holds 10
Try to reassign x = 20?
No→Error: val cannot be reassigned
This flow shows declaring a val variable, holding a value, and that reassignment is not allowed.
val x = 10 println(x) x = 20 // Error
| Step | Action | Variable | Value | Result |
|---|---|---|---|---|
| 1 | Declare val x = 10 | x | 10 | x holds 10 |
| 2 | Print x | x | 10 | Output: 10 |
| 3 | Attempt x = 20 | x | 10 | Error: val cannot be reassigned |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 |
|---|---|---|---|---|
| x | undefined | 10 | 10 | 10 (unchanged, reassignment failed) |
val declares an immutable reference in Kotlin. You assign it once at declaration. Trying to reassign causes a compile-time error. val does not guarantee the object is immutable, only the reference. Use val for constants or references that should not change.