0
0
Kotlinprogramming~5 mins

Object expressions (anonymous objects) in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Object expressions (anonymous objects)
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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 n times, once per loop iteration.
How Execution Grows With Input

Each time we increase n, we create one more object and call its function once.

Input Size (n)Approx. Operations
1010 object creations and 10 function calls
100100 object creations and 100 function calls
10001000 object creations and 1000 function calls

Pattern observation: The work grows evenly with n. Double n, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time needed grows in a straight line with the number of objects created.

Common Mistake

[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.

Interview Connect

Understanding how object creation inside loops affects time helps you write clear and efficient Kotlin code, a skill valued in many coding challenges.

Self-Check

What if we moved the anonymous object creation outside the loop and reused it? How would the time complexity change?