📖 Scenario: Imagine you are building a simple app to manage different types of workers in a company. Some workers have special skills, but you want to reuse existing skill implementations without rewriting code.
🎯 Goal: You will create a Kotlin program that uses class delegation with the by keyword to share behavior between classes easily.
📋 What You'll Learn
Create an interface called Worker with a function work() that returns a String.
Create a class called BasicWorker that implements Worker and returns "Working hard" from work().
Create a class called Manager that delegates Worker behavior to a BasicWorker instance using the by keyword.
Print the result of calling work() on a Manager instance.
💡 Why This Matters
🌍 Real World
Class delegation helps reuse code and share behavior between classes without repeating code. It is useful in apps with many similar roles or behaviors.
💼 Career
Understanding delegation is important for Kotlin developers to write clean, maintainable code and use language features effectively in real projects.
Progress0 / 4 steps
1
Create the Worker interface and BasicWorker class
Create an interface called Worker with a function work() that returns a String. Then create a class called BasicWorker that implements Worker and its work() function returns the exact string "Working hard".
Kotlin
Hint
Use interface to define Worker. Implement work() in BasicWorker to return the string exactly.
2
Create Manager class delegating Worker to BasicWorker
Create a class called Manager that implements Worker by delegating to a BasicWorker instance using the by keyword. Inside Manager, declare a primary constructor parameter called worker of type Worker and delegate Worker to it.
Kotlin
Hint
Use class Manager(private val worker: Worker) : Worker by worker to delegate all Worker functions to the worker instance.
3
Create a Manager instance delegating to BasicWorker
Create a variable called manager and assign it a new Manager instance that delegates to a new BasicWorker instance.
Kotlin
Hint
Use val manager = Manager(BasicWorker()) to create the instance.
4
Print the work result from Manager
Write a println statement to print the result of calling work() on the manager variable.
Kotlin
Hint
Use println(manager.work()) to show the delegated work result.
Practice
(1/5)
1. What does the by keyword do in Kotlin class delegation?
easy
A. It overrides all methods of a class.
B. It creates a new instance of a class.
C. It marks a class as abstract.
D. It lets a class reuse another class's implementation automatically.
Solution
Step 1: Understand the role of by keyword
The by keyword 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 by does
It automatically forwards calls to the delegated class, so the delegating class behaves like the delegated one.
Final Answer:
It lets a class reuse another class's implementation automatically. -> Option D
Quick Check:
Delegation = reuse implementation [OK]
Hint: Remember: by means reuse another class's code [OK]
Common Mistakes:
Thinking by creates a new instance
Confusing by with inheritance
Assuming by overrides methods automatically
2. Which of the following is the correct syntax to delegate interface Printer to class ConsolePrinter in Kotlin?
easy
A. class MyPrinter : Printer by ConsolePrinter()
B. class MyPrinter implements Printer by ConsolePrinter()
C. class MyPrinter extends Printer by ConsolePrinter()
D. class MyPrinter delegate Printer to ConsolePrinter()
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 A
Quick Check:
Syntax = class X : Interface by instance [OK]
Hint: Use colon and 'by' for delegation syntax [OK]
Common Mistakes:
Using 'implements' or 'extends' keywords (Java style)
Writing 'delegate' keyword which doesn't exist
Missing colon before interface name
3. What is the output of this Kotlin code?
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")
}
medium
A. No output
B. Console: Hello
C. Error: log() not implemented
D. Hello
Solution
Step 1: Understand delegation in AppLogger
The class AppLogger delegates Logger interface to the passed logger instance, which is ConsoleLogger.
Step 2: Trace the log call
Calling logger.log("Hello") calls ConsoleLogger.log, which prints "Console: Hello".
Final Answer:
Console: Hello -> Option B
Quick Check:
Delegation calls delegated method output [OK]
Hint: Delegated methods run from the delegated instance [OK]
Common Mistakes:
Expecting just 'Hello' without prefix
Thinking delegation requires manual override
Assuming no output because of delegation
4. Identify the error in this Kotlin code using class delegation:
interface Speaker {
fun speak()
}
class Human : Speaker {
override fun speak() {
println("Hello")
}
}
class Robot(speaker: Speaker) : Speaker {
speak()
}
medium
A. Missing delegation with 'by' keyword in Robot class.
B. Robot class should not implement Speaker interface.
C. Human class must not override speak().
D. speak() method call is correct as is.
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 passed speaker instance using by speaker to avoid error.
Final Answer:
Missing delegation with 'by' keyword in Robot class. -> Option A
Quick Check:
Delegation needs 'by' keyword [OK]
Hint: Delegate with 'by' or implement all methods [OK]
Common Mistakes:
Calling method directly without delegation
Forgetting to use 'by' keyword
Assuming interface methods auto-implement
5. You want to create a class SmartSpeaker that delegates Speaker interface to a Human instance but adds a new method playMusic(). Which is the best way to do this?
hard
A. class SmartSpeaker : Human() {
fun playMusic() = println("Playing music")
}
B. class SmartSpeaker : Speaker {
val human = Human()
override fun speak() = human.speak()
fun playMusic() = println("Playing music")
}
C. class SmartSpeaker(human: Human) : Speaker by human {
fun playMusic() {
println("Playing music")
}
}
D. class SmartSpeaker(human: Human) : Speaker {
fun playMusic() = println("Playing music")
}
Solution
Step 1: Understand delegation with added methods
Using by human delegates all Speaker methods to Human automatically.
Step 2: Add new method in delegating class
We can add playMusic() directly in SmartSpeaker without affecting delegation.
Final Answer:
class SmartSpeaker(human: Human) : Speaker by human {
fun playMusic() {
println("Playing music")
}
} -> Option C
Quick Check:
Delegate with 'by' and add methods [OK]
Hint: Delegate with 'by' and add new methods in class body [OK]
Common Mistakes:
Not delegating interface methods properly
Extending class instead of delegating interface
Forgetting to implement interface methods
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.