Class delegation with the by keyword lets one class use another class's behavior easily. It helps avoid repeating code by passing work to another class.
Class delegation with by keyword in Kotlin
class ClassName(val delegate: InterfaceType) : InterfaceType by delegate
The class ClassName promises to implement InterfaceType.
Instead of writing all methods, it uses by delegate to forward calls to delegate.
DelegatedPrinter that uses ConsolePrinter to do the printing work.interface Printer { fun print() } class ConsolePrinter : Printer { override fun print() { println("Printing on console") } } class DelegatedPrinter(val printer: Printer) : Printer by printer
print method but still delegates other methods.class CountingPrinter(val printer: Printer) : Printer by printer { var count = 0 override fun print() { count++ println("Print called $count times") printer.print() } }
This program shows how BilingualSpeaker uses delegation to speak English or Spanish depending on the delegate passed.
interface Speaker { fun speak() } class EnglishSpeaker : Speaker { override fun speak() { println("Hello!") } } class SpanishSpeaker : Speaker { override fun speak() { println("¡Hola!") } } class BilingualSpeaker(private val speaker: Speaker) : Speaker by speaker fun main() { val english = EnglishSpeaker() val spanish = SpanishSpeaker() val bilingualEnglish = BilingualSpeaker(english) val bilingualSpanish = BilingualSpeaker(spanish) bilingualEnglish.speak() bilingualSpanish.speak() }
Delegation helps keep code clean and easy to maintain.
You can override some methods in the delegating class to add or change behavior.
Delegation works only with interfaces or abstract classes in Kotlin.
Class delegation with by lets one class reuse another's behavior easily.
It helps avoid repeating code and keeps classes focused on their job.
You can add extra features by overriding delegated methods.
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
