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.