0
0
Kotlinprogramming~5 mins

Class delegation with by keyword in Kotlin

Choose your learning style9 modes available
Introduction

Class delegation with the by keyword lets one class use another class's behavior easily. It helps avoid repeating code by passing work to another class.

When you want one class to reuse another class's functions without rewriting them.
When you want to add extra features to a class but keep the original behavior.
When you want to split responsibilities between classes but keep a simple interface.
When you want to change how some methods work but keep others the same.
When you want to follow the rule 'favor composition over inheritance' in your design.
Syntax
Kotlin
class ClassName(val delegate: InterfaceType) : InterfaceType by delegate

The class ClassName promises to implement InterfaceType.

Instead of writing all methods, it uses by delegate to forward calls to delegate.

Examples
This example shows a class DelegatedPrinter that uses ConsolePrinter to do the printing work.
Kotlin
interface Printer {
    fun print()
}

class ConsolePrinter : Printer {
    override fun print() {
        println("Printing on console")
    }
}

class DelegatedPrinter(val printer: Printer) : Printer by printer
This example adds counting behavior by overriding the print method but still delegates other methods.
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 how BilingualSpeaker uses delegation to speak English or Spanish depending on the delegate passed.

Kotlin
interface Speaker {
    fun speak()
}

class EnglishSpeaker : Speaker {
    override fun speak() {
        println("Hello!")
    }
}

class SpanishSpeaker : Speaker {
    override fun speak() {
        println("¡Hola!")
    }
}

class BilingualSpeaker(private val speaker: Speaker) : Speaker by speaker

fun main() {
    val english = EnglishSpeaker()
    val spanish = SpanishSpeaker()

    val bilingualEnglish = BilingualSpeaker(english)
    val bilingualSpanish = BilingualSpeaker(spanish)

    bilingualEnglish.speak()
    bilingualSpanish.speak()
}
OutputSuccess
Important Notes

Delegation helps keep code clean and easy to maintain.

You can override some methods in the delegating class to add or change behavior.

Delegation works only with interfaces or abstract classes in Kotlin.

Summary

Class delegation with by lets one class reuse another's behavior easily.

It helps avoid repeating code and keeps classes focused on their job.

You can add extra features by overriding delegated methods.