What if you could share behavior without the headaches of inheritance?
Why delegation avoids inheritance in Kotlin - The Real Reasons
Imagine you want to create a new class that shares some behavior with an existing class. You try to copy and paste code or use inheritance everywhere, but soon your code becomes tangled and hard to change.
Using inheritance too much makes your code rigid and tightly connected. If the parent class changes, all child classes might break. Also, you can only inherit from one class, which limits flexibility and leads to complex hierarchies.
Delegation lets a class hand off tasks to another class without inheriting from it. This keeps code flexible and easier to maintain because you can change behavior by swapping delegates instead of rewriting or breaking inheritance chains.
open class Animal { open fun move() { println("Moving") } } class Bird : Animal() { override fun move() { println("Flying") } }
interface Movement {
fun move()
}
class Bird(delegate: Movement) : Movement by delegateDelegation enables building flexible, reusable code by sharing behavior without the limits and risks of inheritance.
Think of a smartphone that can use different camera apps. Instead of building all camera features into the phone's main software (inheritance), it delegates photo-taking to whichever app you choose, making it easy to switch or upgrade.
Inheritance can make code rigid and hard to change.
Delegation shares behavior by handing off tasks, not inheriting.
This leads to more flexible and maintainable code.
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
