0
0
Kotlinprogramming~10 mins

Val for immutable references in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Val for immutable references
Declare val x = 10
x holds 10
Try to reassign x = 20?
NoError: val cannot be reassigned
This flow shows declaring a val variable, holding a value, and that reassignment is not allowed.
Execution Sample
Kotlin
val x = 10
println(x)
x = 20 // Error
Declare an immutable val x with 10, print it, then try to reassign (which causes error).
Execution Table
StepActionVariableValueResult
1Declare val x = 10x10x holds 10
2Print xx10Output: 10
3Attempt x = 20x10Error: val cannot be reassigned
💡 Execution stops at step 3 due to reassignment error on val variable.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
xundefined101010 (unchanged, reassignment failed)
Key Moments - 2 Insights
Why can't we assign a new value to a val variable after declaration?
Because val declares an immutable reference, so reassignment is not allowed as shown in execution_table step 3.
Does val mean the value itself is immutable or just the reference?
val means the reference cannot change to point to another object, but the object itself can be mutable if its type allows it.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of x after step 2?
A10
B20
Cundefined
DError
💡 Hint
Check the 'Value' column in execution_table row for step 2.
At which step does the program stop due to an error?
AStep 1
BStep 2
CStep 3
DNo error
💡 Hint
Look at the 'Result' column in execution_table for error messages.
If x was declared with var instead of val, what would happen at step 3?
AError: val cannot be reassigned
Bx would be updated to 20
Cx would remain 10
DProgram would crash
💡 Hint
Recall that var allows reassignment, unlike val, as explained in key_moments.
Concept Snapshot
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.
Full Transcript
In Kotlin, val is used to declare an immutable reference. When you write val x = 10, x holds the value 10 and cannot be reassigned. If you try to assign x = 20 later, the compiler gives an error because val variables cannot be reassigned. The value held by x remains 10 throughout. This means val protects the reference from changing, but if the object itself is mutable, its contents can still change. This example shows declaring val, printing its value, and the error when trying to reassign. Remember, use val when you want a fixed reference.