Interface with default implementations in Kotlin - Time & Space Complexity
We want to understand how the time needed to run code changes when using interfaces with default implementations in Kotlin.
Specifically, how does calling default methods affect the work done as input grows?
Analyze the time complexity of the following code snippet.
interface Printer {
fun printAll(items: List) {
for (item in items) {
print(item)
}
}
}
class ConsolePrinter : Printer
fun main() {
val printer = ConsolePrinter()
val data = List(5) { "Hello" }
printer.printAll(data)
}
This code defines an interface with a default method that prints all items in a list, then uses it in a class.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside the default method
printAllthat goes through each item in the list. - How many times: It runs once for every item in the input list.
As the list size grows, the number of print operations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print calls |
| 100 | 100 print calls |
| 1000 | 1000 print calls |
Pattern observation: The work grows directly with the number of items; doubling items doubles the work.
Time Complexity: O(n)
This means the time to run the method grows in a straight line with the number of items to print.
[X] Wrong: "Using default methods in interfaces makes the code run faster or slower by itself."
[OK] Correct: The default method is just code that runs like any other function; its speed depends on what it does, not where it is defined.
Understanding how default interface methods work helps you explain code design choices and their impact on performance clearly and confidently.
"What if the default method called another method that itself loops over the list? How would the time complexity change?"