Class delegation with by keyword in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run code changes when using class delegation with the by keyword in Kotlin.
Specifically, we ask: how does delegation affect the number of steps the program takes as input grows?
Analyze the time complexity of the following code snippet.
interface Printer {
fun printMessage(message: String)
}
class ConsolePrinter : Printer {
override fun printMessage(message: String) {
println(message)
}
}
class DelegatingPrinter(printer: Printer) : Printer by printer
fun main() {
val printer = DelegatingPrinter(ConsolePrinter())
printer.printMessage("Hello, Kotlin!")
}
This code shows a class DelegatingPrinter that uses the by keyword to delegate its Printer interface methods to another object.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the delegated method
printMessage. - How many times: Exactly once per call in this example.
The program runs the delegated method once each time it is called, regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to printMessage, 10 delegated calls |
| 100 | 100 calls to printMessage, 100 delegated calls |
| 1000 | 1000 calls to printMessage, 1000 delegated calls |
Pattern observation: The number of operations grows directly with the number of calls, one-to-one.
Time Complexity: O(n)
This means the time grows linearly with the number of method calls delegated.
[X] Wrong: "Delegation adds extra loops or slows down the program exponentially."
[OK] Correct: Delegation just forwards calls directly without extra loops, so it does not multiply the work beyond the original calls.
Understanding delegation helps you explain how Kotlin handles code reuse efficiently, a useful skill when discussing design and performance.
What if the delegated method itself contained a loop over input data? How would that affect the overall time complexity?
Practice
by keyword do in Kotlin class delegation?Solution
Step 1: Understand the role of
Thebykeywordbykeyword in Kotlin is used for class delegation, which means one class can reuse the implementation of another class without rewriting the code.Step 2: Identify what
It automatically forwards calls to the delegated class, so the delegating class behaves like the delegated one.bydoesFinal Answer:
It lets a class reuse another class's implementation automatically. -> Option DQuick Check:
Delegation = reuse implementation [OK]
by means reuse another class's code [OK]- Thinking
bycreates a new instance - Confusing
bywith inheritance - Assuming
byoverrides methods automatically
Printer to class ConsolePrinter in Kotlin?Solution
Step 1: Recall Kotlin delegation syntax
In Kotlin, delegation uses the syntax:class ClassName : InterfaceName by instance.Step 2: Match the correct syntax
class MyPrinter : Printer by ConsolePrinter() matches this pattern exactly:class MyPrinter : Printer by ConsolePrinter().Final Answer:
class MyPrinter : Printer by ConsolePrinter() -> Option AQuick Check:
Syntax = class X : Interface by instance [OK]
- Using 'implements' or 'extends' keywords (Java style)
- Writing 'delegate' keyword which doesn't exist
- Missing colon before interface name
interface Logger {
fun log(msg: String)
}
class ConsoleLogger : Logger {
override fun log(msg: String) {
println("Console: $msg")
}
}
class AppLogger(logger: Logger) : Logger by logger
fun main() {
val logger = AppLogger(ConsoleLogger())
logger.log("Hello")
}Solution
Step 1: Understand delegation in
The classAppLoggerAppLoggerdelegatesLoggerinterface to the passedloggerinstance, which isConsoleLogger.Step 2: Trace the
Callinglogcalllogger.log("Hello")callsConsoleLogger.log, which prints "Console: Hello".Final Answer:
Console: Hello -> Option BQuick Check:
Delegation calls delegated method output [OK]
- Expecting just 'Hello' without prefix
- Thinking delegation requires manual override
- Assuming no output because of delegation
interface Speaker {
fun speak()
}
class Human : Speaker {
override fun speak() {
println("Hello")
}
}
class Robot(speaker: Speaker) : Speaker {
speak()
}Solution
Step 1: Check Robot class declaration
Robot implements Speaker but does not delegate or implement speak() method itself.Step 2: Identify missing delegation
Robot should delegate Speaker to the passedspeakerinstance usingby speakerto avoid error.Final Answer:
Missing delegation with 'by' keyword in Robot class. -> Option AQuick Check:
Delegation needs 'by' keyword [OK]
- Calling method directly without delegation
- Forgetting to use 'by' keyword
- Assuming interface methods auto-implement
SmartSpeaker that delegates Speaker interface to a Human instance but adds a new method playMusic(). Which is the best way to do this?Solution
Step 1: Understand delegation with added methods
Usingby humandelegates allSpeakermethods toHumanautomatically.Step 2: Add new method in delegating class
We can addplayMusic()directly inSmartSpeakerwithout affecting delegation.Final Answer:
class SmartSpeaker(human: Human) : Speaker by human { fun playMusic() { println("Playing music") } } -> Option CQuick Check:
Delegate with 'by' and add methods [OK]
- Not delegating interface methods properly
- Extending class instead of delegating interface
- Forgetting to implement interface methods
Ready to prove it?
Pass the test and this pattern moves unknown
