Companion object with interfaces in Kotlin - Time & Space Complexity
Let's see how the time needed to run code with companion objects and interfaces changes as we use more data.
We want to know how the program's work grows when it calls interface methods inside a companion object.
Analyze the time complexity of the following code snippet.
interface Greeter {
fun greet(name: String): String
}
class Person {
companion object : Greeter {
override fun greet(name: String) = "Hello, $name!"
}
}
fun greetAll(names: List) {
for (name in names) {
println(Person.greet(name))
}
}
This code defines an interface and a companion object that implements it. It then greets each name in a list using the companion object.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of names and calling the greet method for each.
- How many times: Once for each name in the input list.
Each new name adds one more greeting call, so the work grows evenly with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greet calls |
| 100 | 100 greet calls |
| 1000 | 1000 greet calls |
Pattern observation: The number of operations grows directly with the number of names.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of names to greet.
[X] Wrong: "Calling a method on a companion object with an interface makes the code slower for each call."
[OK] Correct: Each call runs in constant time; the interface and companion object do not add extra loops or repeated work per call.
Understanding how companion objects and interfaces affect time helps you explain code design choices clearly and confidently.
"What if the greet method itself contained a loop over the input string's characters? How would the time complexity change?"