Kotlin decorator pattern

How to write a decorator pattern in Kotlin

An example of a decorator pattern in Kotlin.

Table of contents for design patterns in Kotlin

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class. Wikipedia

Example:

Printer

interface Printer {
    fun printLetter()
    fun printA4()
}

NormalPrinter

class NormalPrinter: Printer {
    override fun printLetter() {
        println("Print letter")
    }

    override fun printA4() {
        println("Print A4")
    }
}

EnhancedPrinter:

class EnhancedPrinter(private val printer: Printer) : Printer by printer {

    override fun printLetter() {
        println("Setting a color profile")
        printer.printLetter()
    }

    fun printPoster() {
        println("Setting the highest print quality")
        printer.printA4()
    }
}

Usage

fun main() {
    val normalPrinter = NormalPrinter()
    val enhancedPrinter = EnhancedPrinter(normalPrinter)

    enhancedPrinter.apply {
        // normal behavior
        printA4()
        println()

        // overridden behavior
        printLetter()
        println()

        // extended behavior
        printPoster()
    }
}

Result

Print A4

Setting a color profile
Print letter

Setting the highest print quality
Print A4