0
0
Kotlinprogramming~3 mins

Delegation vs inheritance decision in Kotlin - When to Use Which

Choose your learning style9 modes available
The Big Idea

Why rewrite code when you can share it smartly and avoid headaches?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
class Bird {
    fun fly() { println("Flying") }
}

class Penguin {
    fun fly() { println("Can't fly") }
    fun swim() { println("Swimming") }
}
After
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") }
}
What It Enables

It enables you to build flexible, reusable code structures that are easier to maintain and extend.

Real Life Example

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.

Key Takeaways

Manual copying leads to duplicated, hard-to-maintain code.

Inheritance shares behavior by extending classes.

Delegation shares behavior by forwarding tasks to helper objects.