Kotlin
Summary - Delegation
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.
Exercise 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").
Show example 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")
}
Exercise 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.
Show example solution
import kotlin.properties.Delegates
var count by Delegates.observable(0) { _, _, new -> println("New: $new") }
fun main() {
count = 1
count = 2
}
Test yourself
-
Which delegates an interface to an object?
- by lazy
- by (interface)
- by map
- vetoable
Show answer
by (interface) — by (interface) performs class delegation.
-
Match the delegation tools
- by repo
- Class delegation
- by lazy
- Lazy compute
- by map
- Dynamic property
- vetoable
- Validation
Next lesson: value class