🔁 Kotlin – Delegation: Share Behavior Without Inheritance
🧲 Introduction – Why Learn Kotlin Delegation?
Delegation is a Kotlin feature that allows a class to delegate its behavior to another class or object—without using traditional inheritance. This promotes composition over inheritance, enabling more flexible, reusable, and testable designs.
Kotlin simplifies delegation with the powerful by keyword, supporting both interface delegation and property delegation.
🎯 In this guide, you’ll learn:
- What delegation means and why it’s useful
- How to implement interface delegation using
by - How property delegation works (
lazy,observable, custom) - Best practices and real-world use cases
🔄 What Is Delegation?
Delegation means handing off responsibility to another class or object to implement certain functionality.
Instead of:
class A : B() { ... }
You write:
class A(private val b: B) : MyInterface by b
✔️ Kotlin handles all delegated methods behind the scenes.
🔧 Interface Delegation with by
✅ Step-by-step Example:
interface Printer {
fun print(msg: String)
}
class ConsolePrinter : Printer {
override fun print(msg: String) = println("Console: $msg")
}
// Delegate implementation to ConsolePrinter
class ReportPrinter(printer: Printer) : Printer by printer
🔹 Usage:
val report = ReportPrinter(ConsolePrinter())
report.print("Monthly Report") // Output: Console: Monthly Report
✔️ ReportPrinter doesn’t need to override print()—it’s delegated to ConsolePrinter.
🏷️ Property Delegation Basics
✅ 1. lazy – Computed Once, Cached
val config by lazy {
println("Loading config...")
"AppConfig"
}
🔹 Usage:
println(config) // Triggers initialization
println(config) // Uses cached value
🟢 Output:
Loading config...
AppConfig
AppConfig
✅ 2. observable – React to Changes
import kotlin.properties.Delegates
var counter by Delegates.observable(0) { _, old, new ->
println("Counter changed from $old to $new")
}
counter = 5
counter = 10
🟢 Output:
Counter changed from 0 to 5
Counter changed from 5 to 10
✅ 3. vetoable – Conditionally Allow Changes
var score by Delegates.vetoable(0) { _, _, new ->
new <= 100 // Reject values over 100
}
🧩 Custom Property Delegate
You can create your own delegate by implementing ReadOnlyProperty or ReadWriteProperty.
import kotlin.reflect.KProperty
class UpperCaseDelegate : ReadWriteProperty<Any?, String> {
private var value: String = ""
override fun getValue(thisRef: Any?, property: KProperty<*>) = value
override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
this.value = value.uppercase()
}
}
var name: String by UpperCaseDelegate()
name = "kotlin"
println(name) // Output: KOTLIN
🧠 Delegation vs Inheritance
| Feature | Delegation | Inheritance |
|---|---|---|
| Flexibility | ✅ Can change delegate at runtime | ❌ Fixed at compile time |
| Reusability | ✅ Multiple behaviors can be composed | ❌ Single base class |
| Loosely Coupled | ✅ Promotes composition | ❌ Tighter coupling |
| Testing | ✅ Easier to mock | ❌ Harder to isolate |
⚠️ Common Mistakes
| ❌ Mistake | ✅ Fix |
|---|---|
Not using by for delegation | Remember to use by keyword for interface delegation |
| Forgetting delegate contract | Implement the correct delegate interface |
Using lazy where mutation is needed | lazy is read-only; use custom or observable |
✅ Best Practices for Kotlin Delegation
| Practice | Benefit |
|---|---|
| Use interface delegation to avoid inheritance | Promotes modular and reusable components |
Use lazy for heavy one-time values | Improves performance and memory usage |
Use observable for reactive updates | Great for UI state tracking or config changes |
| Keep custom delegates small and focused | Maintain clarity and reduce complexity |
📌 Summary – Recap & Next Steps
Kotlin’s delegation features give you powerful tools to share behavior, manage state dynamically, and build modular systems—all while writing clean, idiomatic code.
🔍 Key Takeaways:
- Use
byfor interface delegation to delegate method calls - Use
lazy,observable, or custom delegates for property control - Delegation supports composition over inheritance
- Perfect for clean architecture, reusable components, and state management
⚙️ Practical Use:
Delegation is ideal for ViewModels, state holders, configuration handlers, service layers, and architecture components in Android and JVM-based Kotlin projects.
❓ FAQs – Kotlin Delegation
❓ What is Kotlin delegation used for?
✅ Delegation lets a class or property forward its behavior to another object—ideal for modular design and clean code.
❓ What is the by keyword in Kotlin?
✅ It’s used to delegate interface methods or property behavior to another class or delegate object.
❓ What is lazy in Kotlin delegation?
✅ A delegate that initializes the value only once—on first access—and caches the result.
❓ Can I have multiple interface delegates in one class?
✅ Not directly. You must manually implement them or use composition inside the class.
❓ What’s the benefit of observable delegation?
✅ It allows you to listen to changes on a property and react immediately—great for UIs or logging.
Share Now :
