0
0
Kotlinprogramming~5 mins

Trailing lambda convention in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Trailing lambda convention
O(n)
Understanding Time Complexity

Let's see how using the trailing lambda style affects how many steps a program takes.

We want to know if this style changes how long the code runs as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

fun processList(items: List<Int>, action: (Int) -> Unit) {
    for (item in items) {
        action(item)
    }
}

// Using trailing lambda convention
processList(listOf(1, 2, 3)) { item ->
    println(item)
}

This code runs an action on each item in a list, using the trailing lambda style for the action.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each item in the list.
  • How many times: Once for every item in the list (n times).
How Execution Grows With Input

Each item causes one action call, so more items mean more steps.

Input Size (n)Approx. Operations
1010 actions
100100 actions
10001000 actions

Pattern observation: The number of steps grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the list gets bigger.

Common Mistake

[X] Wrong: "Using the trailing lambda makes the code run faster."

[OK] Correct: The trailing lambda is just a style choice. It does not change how many times the loop runs or how long the program takes.

Interview Connect

Understanding how code style choices like trailing lambdas affect performance helps you explain your code clearly and confidently.

Self-Check

What if the action inside the lambda also loops over the list? How would the time complexity change?