Delegation trong Kotlin
🎯 Mục tiêu: Hiểu Delegation - pattern composition over inheritance.
💡 Class Delegation
interface Printer {
fun print(message: String)
}
class ConsolePrinter : Printer {
override fun print(message: String) = println(message)
}
class Logger(printer: Printer) : Printer by printer {
// Tất cả methods được delegate cho printer
}📝 Property Delegation
lazy
val expensiveValue: String by lazy {
println("Computing...")
"Result"
}
// Chỉ tính lần đầu truy cậpobservable
import kotlin.properties.Delegates
var name: String by Delegates.observable("Initial") { prop, old, new ->
println("$old -> $new")
}vetoable
var age: Int by Delegates.vetoable(0) { _, _, new ->
new >= 0 // Chỉ chấp nhận nếu >= 0
}✅ Checklist
- Sử dụng class delegation với
by - Sử dụng
lazycho lazy initialization - Sử dụng
observableđể theo dõi thay đổi
Last updated on