Bird
Raised Fist0
Kotlinprogramming~10 mins

Properties with val and var in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Properties with val and var
Declare property with val
↓
Property is read-only
↓
Try to reassign?
Yes→Error: Cannot reassign val
No↓
Declare property with var
↓
Property is mutable
↓
Reassign allowed
↓
Use property value
This flow shows how val creates read-only properties and var creates mutable properties that can be reassigned.
Execution Sample
Kotlin
val name = "Alice"
var age = 30
// name = "Bob" // Error
age = 31
println("$name is $age years old")
This code declares a read-only name and a mutable age, then changes age and prints both.
Execution Table
StepActionPropertyValue BeforeValue AfterOutput/Note
1Declare val namenameundefined"Alice"name set to "Alice"
2Declare var ageageundefined30age set to 30
3Attempt to reassign namename"Alice"ErrorError: Cannot reassign val property
4Reassign ageage3031age changed to 31
5Print statement---"Alice is 31 years old"
💡 Execution stops after print; reassignment to val causes error and is commented out.
Variable Tracker
PropertyStartAfter Step 1After Step 2After Step 3After Step 4Final
nameundefined"Alice""Alice"Error (reassign not allowed)"Alice""Alice"
ageundefinedundefined30303131
Key Moments - 2 Insights
Why can't we change the value of a property declared with val?
Because val properties are read-only after initialization, as shown in step 3 of the execution_table where reassignment causes an error.
Can we change the value of a property declared with var?
Yes, var properties are mutable and can be reassigned, as shown in step 4 where age changes from 30 to 31.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3. What happens when we try to reassign the val property 'name'?
AThe program ignores the reassignment
BThe value changes successfully
CAn error occurs because val properties cannot be reassigned
DThe value becomes null
💡 Hint
Check the 'Output/Note' column at step 3 in the execution_table.
According to variable_tracker, what is the value of 'age' after step 4?
A31
B30
Cundefined
DError
💡 Hint
Look at the 'age' row under 'After Step 4' in variable_tracker.
If we change 'val name' to 'var name', what would happen at step 3?
AAn error would still occur
BReassignment would succeed and name would change
CThe program would crash
DThe value would become null
💡 Hint
Recall that var properties are mutable as explained in the concept_flow and key_moments.
Concept Snapshot
val declares a read-only property (cannot be reassigned).
var declares a mutable property (can be reassigned).
Reassigning val causes a compile-time error.
Use val for constants and var for variables.
Access properties by name to get their current value.
Full Transcript
In Kotlin, properties declared with val are read-only and cannot be changed after they are set. Properties declared with var are mutable and can be reassigned. In the example, 'name' is declared with val and set to "Alice". Trying to change 'name' causes an error. 'age' is declared with var and initially set to 30, then changed to 31 successfully. The program prints the final values. This shows how val and var control mutability of properties.

Practice

(1/5)
1. What is the main difference between val and var properties in Kotlin?
easy
A. val can be changed anytime, var is read-only after initialization.
B. val is read-only after initialization, var can be changed anytime.
C. val and var both can be changed anytime.
D. val and var are exactly the same.

Solution

  1. Step 1: Understand val behavior

    val properties are assigned once and cannot be reassigned later.
  2. Step 2: Understand var behavior

    var properties can be reassigned multiple times after initialization.
  3. Final Answer:

    val is read-only after initialization, var can be changed anytime. -> Option B
  4. Quick Check:

    val = read-only, var = mutable [OK]
Hint: Remember: val = fixed, var = variable [OK]
Common Mistakes:
  • Confusing val as mutable
  • Thinking var is read-only
  • Believing val and var behave the same
2. Which of the following is the correct way to declare a mutable property named age of type Int in Kotlin?
easy
A. var age: Int = 25
B. val age: Int = 25
C. val age = 25
D. var age: Int

Solution

  1. Step 1: Identify mutable property keyword

    Mutable properties use var keyword.
  2. Step 2: Check initialization

    Property must be initialized or declared nullable; here age is initialized with 25.
  3. Final Answer:

    var age: Int = 25 -> Option A
  4. Quick Check:

    Mutable property uses var [OK]
Hint: Use var for changeable properties [OK]
Common Mistakes:
  • Using val for mutable property
  • Not initializing non-nullable property
  • Omitting type without initialization
3. What will be the output of the following Kotlin code?
class Person {
    val name = "Anna"
    var age = 30
}

fun main() {
    val p = Person()
    println(p.name)
    p.age = 31
    println(p.age)
}
medium
A. Anna 30
B. Anna null
C. Error: Cannot assign to val property
D. Anna 31

Solution

  1. Step 1: Check val name usage

    name is a val, so it prints "Anna" and cannot be changed.
  2. Step 2: Check var age reassignment

    age is a var, so it can be changed from 30 to 31 before printing.
  3. Final Answer:

    Anna 31 -> Option D
  4. Quick Check:

    val prints original, var prints updated [OK]
Hint: val prints original, var can be updated [OK]
Common Mistakes:
  • Expecting error on changing var
  • Thinking val can be reassigned
  • Confusing printed values
4. Identify the error in the following Kotlin code:
class Car {
    val model: String
    var year: Int

    init {
        model = "Tesla"
        year = 2020
    }
}

fun main() {
    val car = Car()
    car.model = "BMW"
    println(car.model)
}
medium
A. Cannot assign a new value to val property 'model'.
B. Property 'year' is not initialized.
C. Missing constructor parameters.
D. No error, code runs fine.

Solution

  1. Step 1: Check val model reassignment

    model is declared as val, so it cannot be reassigned after initialization.
  2. Step 2: Verify property initialization

    model and year are both initialized in init, so no initialization error.
  3. Final Answer:

    Cannot assign a new value to val property 'model'. -> Option A
  4. Quick Check:

    val properties cannot be reassigned [OK]
Hint: val properties cannot be changed after init [OK]
Common Mistakes:
  • Trying to reassign val property
  • Ignoring uninitialized var warnings
  • Assuming val can be reassigned
5. You want to create a Kotlin class Book where the title should never change after creation, but the price can be updated. Which declaration is correct?
hard
A. class Book(val title: String, val price: Double)
B. class Book(var title: String, var price: Double)
C. class Book(val title: String, var price: Double)
D. class Book(var title: String, val price: Double)

Solution

  1. Step 1: Determine immutability for title

    title should not change, so declare it with val.
  2. Step 2: Determine mutability for price

    price can change, so declare it with var.
  3. Final Answer:

    class Book(val title: String, var price: Double) -> Option C
  4. Quick Check:

    Immutable title = val, mutable price = var [OK]
Hint: Use val for fixed, var for changeable properties [OK]
Common Mistakes:
  • Using var for title which should be fixed
  • Using val for price which should be changeable
  • Mixing up val and var keywords
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard