Object expressions (anonymous objects) in Kotlin - Time & Space Complexity
Let's see how the time cost changes when we use object expressions, also called anonymous objects, in Kotlin.
We want to know how the program's work grows as we create more of these objects.
Analyze the time complexity of the following code snippet.
fun createObjects(n: Int) {
repeat(n) {
val obj = object {
val x = it
fun greet() = "Hello $x"
}
println(obj.greet())
}
}
This code creates n anonymous objects, each with a property and a function, then prints a greeting.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating an anonymous object and calling its function inside a loop.
- How many times: Exactly
ntimes, once per loop iteration.
Each time we increase n, we create one more object and call its function once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations and 10 function calls |
| 100 | 100 object creations and 100 function calls |
| 1000 | 1000 object creations and 1000 function calls |
Pattern observation: The work grows evenly with n. Double n, double the work.
Time Complexity: O(n)
This means the time needed grows in a straight line with the number of objects created.
[X] Wrong: "Creating anonymous objects inside a loop is free or constant time because they are anonymous."
[OK] Correct: Each object creation takes time, and doing it n times adds up linearly.
Understanding how object creation inside loops affects time helps you write clear and efficient Kotlin code, a skill valued in many coding challenges.
What if we moved the anonymous object creation outside the loop and reused it? How would the time complexity change?