0
0
Kotlinprogramming~5 mins

In variance (contravariance) in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: In variance (contravariance)
O(n)
Understanding Time Complexity

Let's explore how the time cost changes when using in variance (contravariance) in Kotlin generics.

We want to see how the program's work grows as input size changes when using contravariant types.

Scenario Under Consideration

Analyze the time complexity of the following Kotlin code using in variance.


interface Consumer {
    fun consume(item: T)
}

fun feedAll(consumer: Consumer, items: List) {
    for (item in items) {
        consumer.consume(item)
    }
}
    

This code feeds a list of integers to a consumer that accepts numbers using contravariance.

Identify Repeating Operations

Look for loops or repeated actions that affect time.

  • Primary operation: The for loop calling consume for each item.
  • How many times: Once for every item in the items list.
How Execution Grows With Input

As the number of items grows, the loop runs more times, so work grows directly with input size.

Input Size (n)Approx. Operations
1010 consume calls
100100 consume calls
10001000 consume calls

Pattern observation: The work increases in a straight line as input size grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly with the number of items to consume.

Common Mistake

[X] Wrong: "Using in variance changes how many times the loop runs or makes it slower."

[OK] Correct: The variance only affects type safety and compatibility, not how many times the loop executes.

Interview Connect

Understanding how variance affects code helps you reason about type safety and performance separately, a useful skill in real projects.

Self-Check

What if we changed Consumer<Number> to Consumer<Any>? How would the time complexity change?