Unit type as void equivalent in Kotlin - Time & Space Complexity
Let's see how time complexity applies when using Kotlin's Unit type, which is like void in other languages.
We want to know how the program's steps grow when functions return Unit.
Analyze the time complexity of the following code snippet.
fun printNumbers(n: Int): Unit {
for (i in 1..n) {
println(i)
}
}
fun main() {
printNumbers(5)
}
This code prints numbers from 1 to n and returns Unit, meaning it does not return any value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints each number.
- How many times: It runs exactly n times, once for each number.
As n grows, the number of print steps grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print steps |
| 100 | 100 print steps |
| 1000 | 1000 print steps |
Pattern observation: The steps increase directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size n.
[X] Wrong: "Since the function returns Unit, it runs instantly with no cost."
[OK] Correct: Returning Unit just means no value is returned, but the function still does work inside, like the loop here.
Understanding how functions that return Unit behave helps you explain performance clearly and shows you know how Kotlin handles simple procedures.
"What if the function printed only half the numbers, like from 1 to n/2? How would the time complexity change?"