0
0
Kotlinprogramming~5 mins

Why delegation avoids inheritance in Kotlin

Choose your learning style9 modes available
Introduction

Delegation helps reuse code without making classes tightly connected like inheritance does. It keeps things simple and flexible.

When you want to share behavior between classes without forcing a strict parent-child relationship.
When you want to change or extend behavior at runtime without changing the class hierarchy.
When you want to avoid the problems of deep or complicated inheritance trees.
When you want to keep your code easier to understand and maintain.
When you want to combine behaviors from multiple sources without multiple inheritance.
Syntax
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.

Examples
This example shows a class DelegatingPrinter that uses delegation to reuse RealPrinter's print method.
Kotlin
interface Printer {
    fun print()
}

class RealPrinter : Printer {
    override fun print() {
        println("Printing from RealPrinter")
    }
}

class DelegatingPrinter(printer: Printer) : Printer by printer
This example shows how you can add extra behavior while still delegating the main work.
Kotlin
class CountingPrinter(val printer: Printer) : Printer by printer {
    var count = 0
    override fun print() {
        count++
        println("Print called $count times")
        printer.print()
    }
}
Sample Program

This program shows delegation in action. DelegatedSpeaker uses EnglishSpeaker to do the speaking without inheriting from it.

Kotlin
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()
}
OutputSuccess
Important Notes

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.

Summary

Delegation shares behavior without inheritance's tight link.

It makes code easier to change and understand.

Use delegation to combine or extend behavior safely.