In variance (contravariance) in Kotlin - Time & Space 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.
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.
Look for loops or repeated actions that affect time.
- Primary operation: The
forloop callingconsumefor each item. - How many times: Once for every item in the
itemslist.
As the number of items grows, the loop runs more times, so work grows directly with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 consume calls |
| 100 | 100 consume calls |
| 1000 | 1000 consume calls |
Pattern observation: The work increases in a straight line as input size grows.
Time Complexity: O(n)
This means the time to run grows directly with the number of items to consume.
[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.
Understanding how variance affects code helps you reason about type safety and performance separately, a useful skill in real projects.
What if we changed Consumer<Number> to Consumer<Any>? How would the time complexity change?