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?"
Practice
interface in Kotlin?Solution
Step 1: Understand what an interface is
An interface in Kotlin declares functions and properties but does not provide their implementation.Step 2: Compare options with interface purpose
To define a contract with functions and properties without implementation correctly states that interfaces define a contract without implementation. Other options describe features unrelated to interfaces.Final Answer:
To define a contract with functions and properties without implementation -> Option DQuick Check:
Interface = Contract without code [OK]
- Thinking interfaces can create objects directly
- Confusing interfaces with classes that store data
- Believing interfaces inherit from classes
Solution
Step 1: Recall Kotlin interface syntax
Interfaces are declared with the keywordinterfacefollowed by the name and curly braces containing function declarations without parentheses after the name.Step 2: Check each option
interface MyInterface { fun doWork() } matches the correct syntax. class MyInterface { fun doWork() } usesclassinstead ofinterface. fun interface MyInterface { fun doWork() } usesfun interfacewhich is for functional interfaces but requires a single abstract method and different usage. interface MyInterface() { fun doWork() } incorrectly adds parentheses after the interface name.Final Answer:
interface MyInterface { fun doWork() } -> Option AQuick Check:
Interface syntax = interface Name { ... } [OK]
- Using class keyword instead of interface
- Adding parentheses after interface name
- Confusing fun interface with regular interface
interface Greeter {
fun greet(): String
}
class FriendlyGreeter : Greeter {
override fun greet() = "Hello!"
}
fun main() {
val greeter: Greeter = FriendlyGreeter()
println(greeter.greet())
}Solution
Step 1: Understand interface implementation
The interfaceGreeterdeclares a functiongreet(). The classFriendlyGreeterimplements this interface and overridesgreet()to return "Hello!".Step 2: Trace the main function output
Inmain(), an instance ofFriendlyGreeteris assigned to a variable of typeGreeter. Callinggreet()on this instance returns "Hello!" which is printed.Final Answer:
Hello! -> Option CQuick Check:
Interface method call returns overridden string [OK]
- Expecting interface name printed instead of method result
- Thinking it causes compilation error without implementation
- Confusing class name with output
interface Animal {
fun sound(): String
}
class Dog : Animal {
fun sound() = "Bark"
}Solution
Step 1: Check interface function implementation rules
When a class implements an interface function, it must use theoverridekeyword to provide the implementation.Step 2: Analyze the Dog class
TheDogclass definessound()withoutoverride. This causes a compilation error because it does not properly override the interface method.Final Answer:
Dog class must override sound() with 'override' keyword -> Option AQuick Check:
Override keyword required for interface methods [OK]
- Omitting the override keyword
- Thinking interface methods can't have return types
- Making interface implementation optional
main() is run?interface Calculator {
fun calculate(x: Int, y: Int): Int
}
class Adder : Calculator {
override fun calculate(x: Int, y: Int) = x + y
}
class Multiplier : Calculator {
override fun calculate(x: Int, y: Int) = x * y
}
fun main() {
val calculators: List<Calculator> = listOf(Adder(), Multiplier())
for (calc in calculators) {
println(calc.calculate(3, 4))
}
}Solution
Step 1: Understand interface implementations
Two classes implementCalculator:Adderadds two numbers,Multipliermultiplies them.Step 2: Trace the loop output
The list contains anAdderand aMultiplier. Callingcalculate(3,4)onAdderreturns 7, onMultiplierreturns 12. These are printed in order.Final Answer:
7 12 -> Option BQuick Check:
Adder + Multiplier outputs 7 and 12 [OK]
- Mixing order of outputs
- Expecting string concatenation instead of arithmetic
- Thinking interface list causes error
Ready to prove it?
Pass the test and this pattern moves unknown
