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.
val keyword do in Kotlin?valval declares a variable whose reference cannot be changed after assignment.var allows reassignment, but val does not.val = immutable reference [OK]count with value 10 in Kotlin?val is used for immutable variables, and Kotlin infers type if not specified.var (mutable), C has invalid syntax, D is incomplete.val list = mutableListOf(1, 2, 3) list.add(4) println(list)
val means the reference to the list cannot change, but the list itself can be modified.val number = 5 number = 10 println(number)
val variables cannot be reassigned after initialization.number causes a compilation error.val map = mutableMapOf("a" to 1, "b" to 2)
map["a"] = 3
println(map)map is declared with val.val means the reference to the map cannot change, but the map's content can be modified.Pass the test and this pattern moves unknown