What if you could reuse code without rewriting or copying it over and over?
0
0
Why Class delegation with by keyword in Kotlin? - Purpose & Use Cases
The Big Idea
The Scenario
Imagine you have a class that needs to reuse behavior from another class. Without delegation, you must write lots of code to forward each function call manually.
The Problem
This manual forwarding is slow to write, easy to forget or make mistakes, and hard to maintain when the delegated class changes.
The Solution
Class delegation with the by keyword lets Kotlin automatically forward calls to another class, saving time and avoiding errors.
Before vs After
✗ Before
class Printer { fun print() = println("Printing...") } class Manager { private val printer = Printer() fun print() = printer.print() }
✓ After
class Printer { fun print() = println("Printing...") } class Manager(printer: Printer) : Printer by printer
What It Enables
You can easily reuse and extend behavior without writing repetitive forwarding code.
Real Life Example
When building a user interface, you can delegate event handling to another class without rewriting all event methods.
Key Takeaways
Manual forwarding is tedious and error-prone.
by keyword automates delegation.
Code becomes cleaner and easier to maintain.