What is Delegation in Kotlin: Simple Explanation and Example
delegation is a design pattern where an object hands over some of its responsibilities to another object. This allows code reuse and cleaner design by letting one class use the functionality of another without inheritance.How It Works
Delegation in Kotlin works like asking a friend to do a task for you. Instead of doing everything yourself, you pass some jobs to someone else who knows how to do them well. In programming, this means one class can pass certain work to another class, called the delegate.
This helps keep code simple and organized. Instead of repeating the same code in many places, you write it once in the delegate class. Then, other classes can use that code by delegating tasks to it. Kotlin makes this easy with built-in support for delegation, so you don't have to write extra code to forward calls.
Example
This example shows a class Printer that handles printing messages. Another class Manager delegates the printing task to Printer instead of doing it itself.
interface Printer {
fun printMessage(message: String)
}
class RealPrinter : Printer {
override fun printMessage(message: String) {
println("Printing: $message")
}
}
class Manager(printer: Printer) : Printer by printer
fun main() {
val realPrinter = RealPrinter()
val manager = Manager(realPrinter)
manager.printMessage("Hello, delegation!")
}When to Use
Use delegation when you want to share behavior between classes without using inheritance. It is helpful when you want to add features to a class by reusing another class's code. For example, if you have multiple classes that need logging, you can delegate logging to a single logger class.
Delegation is also useful for composing behaviors dynamically and keeping your code flexible and easy to maintain.
Key Points
- Delegation lets one class hand over tasks to another class.
- Kotlin supports delegation natively with the
bykeyword. - It helps avoid code duplication and keeps code clean.
- Delegation is a flexible alternative to inheritance.
Key Takeaways
by keyword makes delegation simple and concise.