What if you could reuse code without rewriting or copying it over and over?
Why Class delegation with by keyword in Kotlin? - Purpose & Use Cases
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.
This manual forwarding is slow to write, easy to forget or make mistakes, and hard to maintain when the delegated class changes.
Class delegation with the by keyword lets Kotlin automatically forward calls to another class, saving time and avoiding errors.
class Printer { fun print() = println("Printing...") } class Manager { private val printer = Printer() fun print() = printer.print() }
class Printer { fun print() = println("Printing...") } class Manager(printer: Printer) : Printer by printer
You can easily reuse and extend behavior without writing repetitive forwarding code.
When building a user interface, you can delegate event handling to another class without rewriting all event methods.
Manual forwarding is tedious and error-prone.
by keyword automates delegation.
Code becomes cleaner and easier to maintain.
Practice
by keyword do in Kotlin class delegation?Solution
Step 1: Understand the role of
Thebykeywordbykeyword in Kotlin is used for class delegation, which means one class can reuse the implementation of another class without rewriting the code.Step 2: Identify what
It automatically forwards calls to the delegated class, so the delegating class behaves like the delegated one.bydoesFinal Answer:
It lets a class reuse another class's implementation automatically. -> Option DQuick Check:
Delegation = reuse implementation [OK]
by means reuse another class's code [OK]- Thinking
bycreates a new instance - Confusing
bywith inheritance - Assuming
byoverrides methods automatically
Printer to class ConsolePrinter in Kotlin?Solution
Step 1: Recall Kotlin delegation syntax
In Kotlin, delegation uses the syntax:class ClassName : InterfaceName by instance.Step 2: Match the correct syntax
class MyPrinter : Printer by ConsolePrinter() matches this pattern exactly:class MyPrinter : Printer by ConsolePrinter().Final Answer:
class MyPrinter : Printer by ConsolePrinter() -> Option AQuick Check:
Syntax = class X : Interface by instance [OK]
- Using 'implements' or 'extends' keywords (Java style)
- Writing 'delegate' keyword which doesn't exist
- Missing colon before interface name
interface Logger {
fun log(msg: String)
}
class ConsoleLogger : Logger {
override fun log(msg: String) {
println("Console: $msg")
}
}
class AppLogger(logger: Logger) : Logger by logger
fun main() {
val logger = AppLogger(ConsoleLogger())
logger.log("Hello")
}Solution
Step 1: Understand delegation in
The classAppLoggerAppLoggerdelegatesLoggerinterface to the passedloggerinstance, which isConsoleLogger.Step 2: Trace the
Callinglogcalllogger.log("Hello")callsConsoleLogger.log, which prints "Console: Hello".Final Answer:
Console: Hello -> Option BQuick Check:
Delegation calls delegated method output [OK]
- Expecting just 'Hello' without prefix
- Thinking delegation requires manual override
- Assuming no output because of delegation
interface Speaker {
fun speak()
}
class Human : Speaker {
override fun speak() {
println("Hello")
}
}
class Robot(speaker: Speaker) : Speaker {
speak()
}Solution
Step 1: Check Robot class declaration
Robot implements Speaker but does not delegate or implement speak() method itself.Step 2: Identify missing delegation
Robot should delegate Speaker to the passedspeakerinstance usingby speakerto avoid error.Final Answer:
Missing delegation with 'by' keyword in Robot class. -> Option AQuick Check:
Delegation needs 'by' keyword [OK]
- Calling method directly without delegation
- Forgetting to use 'by' keyword
- Assuming interface methods auto-implement
SmartSpeaker that delegates Speaker interface to a Human instance but adds a new method playMusic(). Which is the best way to do this?Solution
Step 1: Understand delegation with added methods
Usingby humandelegates allSpeakermethods toHumanautomatically.Step 2: Add new method in delegating class
We can addplayMusic()directly inSmartSpeakerwithout affecting delegation.Final Answer:
class SmartSpeaker(human: Human) : Speaker by human { fun playMusic() { println("Playing music") } } -> Option CQuick Check:
Delegate with 'by' and add methods [OK]
- Not delegating interface methods properly
- Extending class instead of delegating interface
- Forgetting to implement interface methods
Ready to prove it?
Pass the test and this pattern moves unknown
