Primary constructor and init blocks in Kotlin - Time & Space Complexity
We want to understand how the time it takes to create an object grows when using primary constructors and init blocks in Kotlin.
How does the number of steps change as we add more properties or logic inside the init block?
Analyze the time complexity of the following code snippet.
class Person(val name: String, val age: Int) {
init {
println("Creating person: $name, age $age")
}
}
fun main() {
val people = List(1000) { Person("Name$it", it) }
}
This code creates 1000 Person objects using a primary constructor and an init block that prints a message for each object.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating each Person object and running its init block.
- How many times: The init block runs once per object, so 1000 times in this example.
Each new object requires running the constructor and init block once, so the total steps grow directly with the number of objects.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 constructor + 10 init calls = 20 steps |
| 100 | 100 constructor + 100 init calls = 200 steps |
| 1000 | 1000 constructor + 1000 init calls = 2000 steps |
Pattern observation: The total work doubles the input size because each object triggers one constructor and one init block call.
Time Complexity: O(n)
This means the time to create objects grows linearly with the number of objects created.
[X] Wrong: "The init block runs only once no matter how many objects are created."
[OK] Correct: Each object creation triggers its own init block, so it runs once per object, not just once total.
Understanding how constructors and init blocks affect performance helps you write efficient Kotlin classes and shows you can reason about object creation costs.
"What if the init block contained a loop that runs m times? How would the time complexity change with respect to n and m?"