Properties with val and var in Kotlin - Time & Space Complexity
Let's see how the time it takes to access or change properties grows when using val and var in Kotlin.
We want to know how the program's speed changes as we work with these properties more.
Analyze the time complexity of the following code snippet.
class Person(val name: String, var age: Int) {
fun celebrateBirthday() {
age += 1
}
}
fun main() {
val people = List(1000) { Person("Name$it", 20) }
for (person in people) {
println(person.name)
person.celebrateBirthday()
}
}
This code creates a list of people with fixed names and ages that can change. It prints each name and increases each person's age by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of people to access
valand modifyvarproperties. - How many times: Once for each person in the list (1000 times in this example).
Each person is handled one by one, so if we have more people, the work grows evenly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 property accesses and updates |
| 100 | 100 property accesses and updates |
| 1000 | 1000 property accesses and updates |
Pattern observation: The work grows directly with the number of people. Double the people, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of properties accessed or changed.
[X] Wrong: "Accessing a val property is slower than a var because it cannot change."
[OK] Correct: Both val and var properties are accessed quickly; the difference is only if you can change the value, not how fast you get it.
Understanding how property access and updates scale helps you explain how your code behaves with more data, a skill useful in many programming tasks.
"What if we added a nested loop inside celebrateBirthday() that runs a fixed number of times? How would the time complexity change?"
Practice
val and var properties in Kotlin?Solution
Step 1: Understand
valbehaviorvalproperties are assigned once and cannot be reassigned later.Step 2: Understand
varbehaviorvarproperties can be reassigned multiple times after initialization.Final Answer:
valis read-only after initialization,varcan be changed anytime. -> Option BQuick Check:
val= read-only,var= mutable [OK]
- Confusing val as mutable
- Thinking var is read-only
- Believing val and var behave the same
age of type Int in Kotlin?Solution
Step 1: Identify mutable property keyword
Mutable properties usevarkeyword.Step 2: Check initialization
Property must be initialized or declared nullable; hereageis initialized with 25.Final Answer:
var age: Int = 25 -> Option AQuick Check:
Mutable property usesvar[OK]
- Using val for mutable property
- Not initializing non-nullable property
- Omitting type without initialization
class Person {
val name = "Anna"
var age = 30
}
fun main() {
val p = Person()
println(p.name)
p.age = 31
println(p.age)
}Solution
Step 1: Check
val nameusagenameis aval, so it prints "Anna" and cannot be changed.Step 2: Check
var agereassignmentageis avar, so it can be changed from 30 to 31 before printing.Final Answer:
Anna 31 -> Option DQuick Check:
valprints original,varprints updated [OK]
- Expecting error on changing var
- Thinking val can be reassigned
- Confusing printed values
class Car {
val model: String
var year: Int
init {
model = "Tesla"
year = 2020
}
}
fun main() {
val car = Car()
car.model = "BMW"
println(car.model)
}Solution
Step 1: Check
val modelreassignmentmodelis declared asval, so it cannot be reassigned after initialization.Step 2: Verify property initialization
modelandyearare both initialized ininit, so no initialization error.Final Answer:
Cannot assign a new value to val property 'model'. -> Option AQuick Check:
val properties cannot be reassigned [OK]
- Trying to reassign val property
- Ignoring uninitialized var warnings
- Assuming val can be reassigned
Book where the title should never change after creation, but the price can be updated. Which declaration is correct?Solution
Step 1: Determine immutability for
titletitleshould not change, so declare it withval.Step 2: Determine mutability for
pricepricecan change, so declare it withvar.Final Answer:
class Book(val title: String, var price: Double) -> Option CQuick Check:
Immutable title = val, mutable price = var [OK]
- Using var for title which should be fixed
- Using val for price which should be changeable
- Mixing up val and var keywords
Ready to prove it?
Pass the test and this pattern moves unknown
