Delegation helps reuse code without making classes tightly connected like inheritance does. It keeps things simple and flexible.
Why delegation avoids inheritance in Kotlin
class Derived(delegate: Base) : Base by delegate
The by keyword tells Kotlin to delegate all calls of Base interface to the delegate object.
This means Derived does not inherit from Base but uses its implementation.
DelegatingPrinter that uses delegation to reuse RealPrinter's print method.interface Printer { fun print() } class RealPrinter : Printer { override fun print() { println("Printing from RealPrinter") } } class DelegatingPrinter(printer: Printer) : Printer by printer
class CountingPrinter(val printer: Printer) : Printer by printer { var count = 0 override fun print() { count++ println("Print called $count times") printer.print() } }
This program shows delegation in action. DelegatedSpeaker uses EnglishSpeaker to do the speaking without inheriting from it.
interface Speaker { fun speak() } class EnglishSpeaker : Speaker { override fun speak() { println("Hello!") } } class DelegatedSpeaker(val speaker: Speaker) : Speaker by speaker fun main() { val english = EnglishSpeaker() val delegated = DelegatedSpeaker(english) delegated.speak() }
Delegation avoids the tight coupling that inheritance creates.
You can change the delegate object anytime if you keep a reference, making your code more flexible.
Delegation helps keep your classes focused on one job each.
Delegation shares behavior without inheritance's tight link.
It makes code easier to change and understand.
Use delegation to combine or extend behavior safely.
Practice
Solution
Step 1: Understand inheritance coupling
Inheritance creates a strong link between parent and child classes, making changes harder.Step 2: Understand delegation flexibility
Delegation shares behavior by forwarding calls, avoiding tight coupling and allowing easier changes.Final Answer:
Delegation allows sharing behavior without tightly coupling classes. -> Option CQuick Check:
Delegation avoids tight coupling = A [OK]
- Thinking delegation is faster than inheritance
- Believing Kotlin does not support inheritance
- Confusing delegation with less code requirement
Printer by a class Document?Solution
Step 1: Recall Kotlin delegation syntax
Kotlin usesclass ClassName(...) : Interface by instanceto delegate.Step 2: Match syntax to options
class Document(printer: Printer) : Printer by printer matches the correct Kotlin delegation syntax exactly.Final Answer:
class Document(printer: Printer) : Printer by printer -> Option AQuick Check:
Delegation syntax uses ': Interface by instance' = B [OK]
- Using 'implements' or 'extends' keywords (Java style)
- Placing delegation inside parentheses incorrectly
- Confusing inheritance syntax with delegation
interface Logger {
fun log(msg: String)
}
class ConsoleLogger : Logger {
override fun log(msg: String) {
println("Console: $msg")
}
}
class FileLogger : Logger {
override fun log(msg: String) {
println("File: $msg")
}
}
class Application(logger: Logger) : Logger by logger
fun main() {
val app = Application(ConsoleLogger())
app.log("Start")
}Solution
Step 1: Identify delegated logger instance
The Application class delegates Logger to the passed instance, here ConsoleLogger.Step 2: Trace the log call
Calling app.log("Start") calls ConsoleLogger.log, printing "Console: Start".Final Answer:
Console: Start -> Option BQuick Check:
Delegation calls ConsoleLogger.log = A [OK]
- Assuming FileLogger is used instead of ConsoleLogger
- Expecting Application prefix in output
- Thinking no output occurs without explicit print
interface Worker {
fun work()
}
class Engineer : Worker {
override fun work() {
println("Engineering work")
}
}
class Manager(worker: Worker) : Worker {
override fun work() {
println("Managing")
}
}Solution
Step 1: Check delegation usage
Manager has a Worker parameter but does not delegate using 'by', so delegation is missing.Step 2: Identify correct delegation syntax
To delegate, Manager should declare:class Manager(worker: Worker) : Worker by worker.Final Answer:
Manager should delegate work to Worker using 'by' keyword. -> Option AQuick Check:
Missing 'by' keyword for delegation = D [OK]
- Thinking override is not needed in Engineer
- Believing interfaces can't be implemented
- Assuming constructor parameters are disallowed
Reader and Writer in one class without inheritance. Which Kotlin approach best avoids inheritance problems?Solution
Step 1: Understand multiple inheritance issues
Inheriting from multiple interfaces can cause tight coupling and complexity.Step 2: Use delegation to combine behaviors safely
Delegation allows combining behaviors by forwarding calls to separate instances, avoiding inheritance problems.Final Answer:
Use delegation to both interfaces by passing separate instances. -> Option DQuick Check:
Delegation combines behaviors safely = C [OK]
- Trying multiple inheritance which Kotlin disallows
- Manually copying methods causing code duplication
- Mixing inheritance and manual implementation causing complexity
Ready to prove it?
Pass the test and this pattern moves unknown
