Decorators in Kotlin help you add new functionality to objects without changing their structure. They promote clean, reusable, and flexible code. By using Kotlin’s features like delegation and extension functions, you can simplify decorator implementation.
Following best practices such as reducing redundant code, maintaining a single responsibility, and thorough testing ensures efficient and maintainable decorators.
In this blog, we’ll explore how to design, optimize, and debug Kotlin decorators to create scalable solutions for real-world applications.
Have you needed to add new functionality to a class without modifying its existing code? The decorator pattern provides a solution by allowing dynamic modification of an existing class without altering its core. It’s one of the most flexible and widely used design patterns.
The decorator pattern works by wrapping an existing class with a decorator class. This wrapper intercepts method calls, adding or modifying behavior dynamically. Unlike the builder design pattern or singleton design pattern, the decorator is ideal for cases where new behaviors need to be added at runtime.
Kotlin streamlines the decorator pattern with its concise syntax and powerful features. Leveraging interfaces, abstract classes, and higher-order functions, Kotlin eliminates much of the boilerplate code seen in other languages.
fun methods in an abstract class ensures cleaner, modular code.interface Vehicle { fun drive(): String } class BasicCar : Vehicle { override fun drive() = "Driving a basic car" } class SportsCar(private val vehicle: Vehicle) : Vehicle { override fun drive(): String { return vehicle.drive() + " with enhanced speed" } } class LuxuryCar(private val vehicle: Vehicle) : Vehicle { override fun drive(): String { return vehicle.drive() + " with luxury features" } } fun main() { val basicCar: Vehicle = BasicCar() val sportsCar: Vehicle = SportsCar(basicCar) val luxuryCar: Vehicle = LuxuryCar(basicCar) println(basicCar.drive()) // Output: Driving a basic car println(sportsCar.drive()) // Output: Driving a basic car with enhanced speed println(luxuryCar.drive()) // Output: Driving a basic car with luxury features }
In this example:
Vehicle interface.This approach is modular, adheres to object composition, and avoids altering the original class.
The decorator pattern is a cornerstone of design patterns when it comes to improving code modularity. By separating additional behavior into decorator classes, you ensure that your code adheres to the Single Responsibility Principle. Each decorator handles a specific new functionality, leaving the original object untouched.
For instance, in Kotlin, decorators allow you to enhance the basic car functionality by wrapping it with new behaviors such as luxury or offroad capabilities without making any changes to the existing class.
interface Coffee { fun getDescription(): String fun getCost(): Double } class BasicCoffee : Coffee { override fun getDescription() = "Basic Coffee" override fun getCost() = 2.0 } class MilkDecorator(private val coffee: Coffee) : Coffee { override fun getDescription() = coffee.getDescription() + ", with Milk" override fun getCost() = coffee.getCost() + 0.5 } class SugarDecorator(private val coffee: Coffee) : Coffee { override fun getDescription() = coffee.getDescription() + ", with Sugar" override fun getCost() = coffee.getCost() + 0.3 }
Here, the decorators MilkDecorator and SugarDecorator work independently of the BasicCoffee class, maintaining a clean structure and modular design.
The decorator pattern in Kotlin is especially powerful because it allows you to modify object behavior at runtime. By wrapping an individual object with a decorator, you can dynamically adjust its functionality based on user input, environment, or other factors.
fun configureCar(isLuxury: Boolean): Car { val basicCar = BasicCar() return if (isLuxury) LuxuryCar(basicCar) else OffroadCar(basicCar) } fun main() { val car = configureCar(isLuxury = true) println(car.drive()) }
The configureCar function dynamically wraps the BasicCar with either a LuxuryCar or an OffroadCar, depending on runtime input.
Decorators promote code reusability by allowing the same decorator class to be applied to multiple component objects. This means you can reuse a single decorator to add new features across different implementations of a shared interface or abstract class.
fun main() { val coffee: Coffee = SugarDecorator(MilkDecorator(BasicCoffee())) println("${coffee.getDescription()} costs \$${coffee.getCost()}") // Output: Basic Coffee, with Milk, with Sugar costs $2.8 }
This demonstrates how multiple decorators can be combined to add functionality progressively, enabling scalable designs for real projects.
When creating decorator classes in Kotlin, it’s crucial to design them in a way that maintains clarity and modularity. A well-structured decorator adheres to these principles:
interface Notifier { fun send(message: String) } class BasicNotifier : Notifier { override fun send(message: String) { println("Sending notification: $message") } } class SMSNotifier(private val notifier: Notifier) : Notifier { override fun send(message: String) { notifier.send(message) println("Sending SMS: $message") } } class EmailNotifier(private val notifier: Notifier) : Notifier { override fun send(message: String) { notifier.send(message) println("Sending Email: $message") } } fun main() { val basicNotifier = BasicNotifier() val smsNotifier = SMSNotifier(basicNotifier) val emailNotifier = EmailNotifier(smsNotifier) emailNotifier.send("Decorator pattern in Kotlin is awesome!") }
Here:
Reducing boilerplate code is key to writing clean and maintainable decorators in Kotlin. Kotlin’s concise syntax and features such as delegation, extension functions, and higher-order functions help achieve this.
by keyword simplifies the implementation of decorators by delegating unaltered method calls to the wrapped object.class LoggingNotifier(private val notifier: Notifier) : Notifier by notifier { override fun send(message: String) { println("Logging: $message") notifier.send(message) } }
fun Notifier.withLogging(): Notifier = object : Notifier { override fun send(message: String) { println("Logging: $message") this@withLogging.send(message) } }
fun logAndSend(notify: (String) -> Unit): (String) -> Unit { return { message -> println("Logging: $message") notify(message) } }
Each decorator class should have a well-defined purpose. The Single Responsibility Principle (SRP) ensures that a decorator modifies only a specific aspect of behavior without interfering with other decorators or the core functionality.
Testing and debugging decorator implementations can be tricky, especially when they are stacked. Proper testing ensures that each decorator works independently and in combination with others.
@Test fun testSMSNotifier() { val basicNotifier = BasicNotifier() val smsNotifier = SMSNotifier(basicNotifier) val output = smsNotifier.send("Test Message") assertEquals("Sending notification: Test Message\nSending SMS: Test Message", output) }
@Test fun testCombinedNotifiers() { val basicNotifier = BasicNotifier() val smsNotifier = SMSNotifier(basicNotifier) val emailNotifier = EmailNotifier(smsNotifier) val output = emailNotifier.send("Test Message") assertEquals( "Sending notification: Test Message\nSending SMS: Test Message\nSending Email: Test Message", output ) }
Use Mocking Frameworks: Use Kotlin’s testing libraries like MockK to verify that decorators call the wrapped component correctly.
Log Outputs: Add logging statements in decorators to debug their behavior during execution.

Build 10x products in minutes by chatting with AI - beyond just a prototype.
What is the Kotlin Decorator pattern used for?
How does Kotlin simplify implementing decorators?
What are the best practices for Kotlin decorators?