Skip to content

what is delegation in kotlin

Devrath edited this page Feb 25, 2024 · 26 revisions

In Kotlin, delegation is a design pattern that allows one class to use the functionalities of another class by delegating some of its responsibilities to the delegated class. This is achieved using the by keyword in Kotlin.

By using delegation, a class can reuse code from another class without directly inheriting from it. This promotes code reuse and composition over inheritance, which can lead to more flexible and maintainable code.

Here's a simple example to illustrate delegation in Kotlin:

Code

interface Printer {
    fun printMessage(message: String)
}

class BasicPrinter : Printer {
    override fun printMessage(message: String) {
        println("BasicPrinter: $message")
    }
}

class DecoratedPrinter(printer: Printer) : Printer by printer

fun main() {
    val basicPrinter = BasicPrinter()
    val decoratedPrinter = DecoratedPrinter(basicPrinter)

    decoratedPrinter.printMessage("Hello, Kotlin!")
}

Output

BasicPrinter: Hello, Kotlin!

In this example, BasicPrinter is a class that implements the Printer interface. DecoratedPrinter is another class that also implements the Printer interface but delegates the printMessage function to an instance of Printer passed in its constructor. This means that DecoratedPrinter does not contain the actual implementation of printMessage but relies on the delegated Printer instance to perform the printing.

When you create an instance of DecoratedPrinter and call its printMessage function, it uses the implementation from the BasicPrinter class.

Delegation allows you to compose objects and build more modular and reusable components in your code.

Clone this wiki locally