0
0
Kotlinprogramming~5 mins

SAM conversions for Java interfaces in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: SAM conversions for Java interfaces
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code changes when using SAM conversions for Java interfaces in Kotlin.

Specifically, how does the cost grow when we create many instances using SAM conversions?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun createRunnables(n: Int): List {
    return List(n) { i ->
        Runnable { println("Running task $i") }
    }
}
    

This code creates a list of n Runnable objects using SAM conversion from a lambda.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating a Runnable instance inside a loop.
  • How many times: Exactly n times, once per list element.
How Execution Grows With Input

Each Runnable is created once per loop iteration, so the total work grows directly with n.

Input Size (n)Approx. Operations
1010 Runnable creations
100100 Runnable creations
10001000 Runnable creations

Pattern observation: The work increases evenly as n grows; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all Runnable instances grows in a straight line with the number of instances.

Common Mistake

[X] Wrong: "SAM conversions make instance creation instant or free."

[OK] Correct: Each SAM conversion still creates a new object, so the time grows with how many you make.

Interview Connect

Understanding how SAM conversions affect performance helps you write clear and efficient Kotlin code when working with Java interfaces.

Self-Check

What if we reused a single Runnable instance instead of creating one per loop? How would the time complexity change?