Interface declaration and implementation in Kotlin - Time & Space Complexity
When we use interfaces in Kotlin, we want to know how the program's speed changes as we add more code or objects that use these interfaces.
We ask: How does the time to run grow when we create and use many implementations of an interface?
Analyze the time complexity of the following code snippet.
interface Greeter {
fun greet()
}
class FriendlyGreeter : Greeter {
override fun greet() {
println("Hello!")
}
}
fun greetAll(greeters: List) {
for (greeter in greeters) {
greeter.greet()
}
}
This code defines an interface and a class that implements it. Then it calls the greet method on each object in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of greeters and calling greet()
- How many times: Once for each greeter in the list (n times)
Each new greeter added means one more greet() call, so the total work grows evenly with the number of greeters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greet() calls |
| 100 | 100 greet() calls |
| 1000 | 1000 greet() calls |
Pattern observation: The work grows in a straight line as we add more greeters.
Time Complexity: O(n)
This means the time to greet everyone grows directly with the number of greeters.
[X] Wrong: "Calling greet() on each object is constant time no matter how many objects there are."
[OK] Correct: Each greet() call happens once per object, so more objects mean more calls and more time.
Understanding how loops over interface implementations scale helps you explain how your code handles many objects efficiently.
"What if greet() itself contained a loop over a list of messages? How would the time complexity change?"