by
- Kotlin course
- Intermediate
- Lesson 70/116
- 5 min
Learn class delegation with by.
Class delegation with by
In Kotlin the by keyword lets a class delegate the implementation of an interface to another object. Example: class Service(logger: Logger) : Logger by logger. Here Service implements the Logger interface but forwards all Logger methods to the logger parameter.
This is a concise way to use composition over inheritance. Service can override specific methods if needed and delegate the rest. It enables code reuse without the rigidity of inheritance.
Delegation vs inheritance
Delegation provides composition instead of inheritance. With inheritance a subclass is tightly coupled to its parent; with delegation a class wraps an object and forwards work to it. A class can inherit from only one class but delegate to many interfaces.
Example: class Repo(db: Db) : Db by db, Cache by cache delegates two interfaces to two different objects. Delegation also allows swapping the target at runtime, which inheritance cannot. Injecting a fake object for testing is easier.
Practice Set up Logger delegation
Define interface Logger { fun log(message: String) }. In class ConsoleLogger : Logger write override fun log(message: String) = println(message). Define class Service(logger: Logger) : Logger by logger. In main create Service(ConsoleLogger()) and call service.log("Running").
Starter code
interface Logger {
fun log(message: String)
}
class ConsoleLogger : Logger {
override fun log(message: String) = println(message)
}
// Define the Service class: Logger delegation via logger
fun main() {
val service = Service(ConsoleLogger())
// Call service.log
}Sample solution
interface Logger {
fun log(message: String)
}
class ConsoleLogger : Logger {
override fun log(message: String) = println(message)
}
class Service(logger: Logger) : Logger by logger
fun main() {
val service = Service(ConsoleLogger())
service.log("Running")
}Expected output
Running
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does class Service(logger: Logger) : Logger by logger do?
- Only calls the constructor
- Delegates Logger methods to logger Correct answer
- Creates a new Logger
- Hides the methods
Explanation: by logger forwards Logger methods to the logger object.
2 Complete the delegation declaration
class Service(logger: Logger) : Logger ____ logger
class Service(logger: Logger) : Logger by logger
Explanation: by logger marks delegation.
3 Match the delegation parts
| Term | Meaning |
|---|---|
by |
Delegation |
interface Logger |
Contract |
class Service |
Client |
logger |
Target |