Summary - Delegation
- Kotlin course
- Intermediate
- Lesson 75/116
- 5 min
Combine by, lazy and custom delegates to write a cache system.
Summary - Delegation
In this group you learned five delegation tools. by lets a class delegate interface methods to another object. by lazy provides deferred computation, by observable provides change tracking.
by map reads properties from a map. vetoable rejects assignments by condition. A custom delegate fully controls behavior with getValue and setValue operators. Each tool is a powerful path for composition and code reuse.
Choosing the right delegation
Pick the tool for the job: by for class delegation, by lazy for deferred computation, observable for change tracking. Use by map for dynamic data, vetoable for validation, a custom delegate for full control.
These tools provide composition over inheritance; they keep classes flexible. Real needs like delegating a logger, lazy-loading configuration or rejecting a negative age are solved in clean single lines. The business requirement decides which tool fits.
Practice Combine class delegation and by lazy
Define interface Greeter { fun greet(): String }. In class EnglishGreeter : Greeter write override fun greet() = "Hello". Define class App(g: Greeter) : Greeter by g. Define val tag by lazy { "v1" }. In main create val app = App(EnglishGreeter()) and call println("${app.greet()} $tag").
Starter code
interface Greeter {
fun greet(): String
}
class EnglishGreeter : Greeter {
override fun greet() = "Hello"
}
// Define the App class: Greeter delegation via g
// Define tag with the lazy delegate
fun main() {
val app = App(EnglishGreeter())
// Print with greet and tag
}Sample solution
interface Greeter {
fun greet(): String
}
class EnglishGreeter : Greeter {
override fun greet() = "Hello"
}
class App(g: Greeter) : Greeter by g
val tag by lazy { "v1" }
fun main() {
val app = App(EnglishGreeter())
println("${app.greet()} $tag")
}Expected output
Hello v1
Practice Track changes with observable
Add import kotlin.properties.Delegates. Define var count by Delegates.observable(0) { _, _, new -> println("New: $new") }. In main assign count = 1 and count = 2.
Starter code
import kotlin.properties.Delegates
// Define count with the observable delegate
fun main() {
// Assign 1 and 2 to count
}Sample solution
import kotlin.properties.Delegates
var count by Delegates.observable(0) { _, _, new -> println("New: $new") }
fun main() {
count = 1
count = 2
}Expected output
New: 1 New: 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which delegates an interface to an object?
- by lazy
- by (interface) Correct answer
- by map
- vetoable
Explanation: by (interface) performs class delegation.
2 Match the delegation tools
| Term | Meaning |
|---|---|
by repo |
Class delegation |
by lazy |
Lazy compute |
by map |
Dynamic property |
vetoable |
Validation |