Why rewrite code when you can share it smartly and avoid headaches?
Delegation vs inheritance decision in Kotlin - When to Use Which
Imagine you want to create a new class that shares some behavior with an existing class. You try to copy and paste code or manually rewrite similar functions in the new class.
This manual copying is slow and error-prone. If the original behavior changes, you must update every copy. It becomes a mess to maintain and easy to introduce bugs.
Using delegation or inheritance lets you reuse behavior cleanly. Inheritance lets a class inherit behavior directly, while delegation lets a class hand off tasks to another object. Both avoid code duplication and make updates easier.
class Bird { fun fly() { println("Flying") } } class Penguin { fun fly() { println("Can't fly") } fun swim() { println("Swimming") } }
interface Flyer { fun fly() }
class Bird : Flyer {
override fun fly() { println("Flying") }
}
class Penguin(private val flyer: Flyer) : Flyer by flyer {
fun swim() { println("Swimming") }
}It enables you to build flexible, reusable code structures that are easier to maintain and extend.
Think of a smartphone app where some features come from a shared library (inheritance), and others are added by plugging in helper objects (delegation) to customize behavior without rewriting code.
Manual copying leads to duplicated, hard-to-maintain code.
Inheritance shares behavior by extending classes.
Delegation shares behavior by forwarding tasks to helper objects.