在Kotlin中,委托是一種機制,允許一個對象將某些特定的行為委托給另一個對象。委托可以減少代碼的重復和提高代碼的可復用性。在Kotlin中,使用關鍵字by
來實現委托。
委托分為兩種類型:類委托和屬性委托。
interface Printer {
fun print()
}
class PrinterImpl : Printer {
override fun print() {
println("Printing...")
}
}
class DelegatePrinter(val printer: Printer) : Printer by printer
fun main() {
val printerImpl = PrinterImpl()
val delegatePrinter = DelegatePrinter(printerImpl)
delegatePrinter.print() // 輸出:Printing...
}
lazy
、observable
等。class Example {
var p: String by Delegate()
}
class Delegate {
operator fun getValue(thisRef: Any?, prop: KProperty<*>): String {
return "$thisRef, delegated property is ${prop.name}"
}
operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) {
println("$value has been assigned to '${prop.name}' in $thisRef.")
}
}
fun main() {
val e = Example()
println(e.p) // 輸出:Example@xxxxxx, delegated property is p
e.p = "New value" // 輸出:New value has been assigned to 'p' in Example@xxxxxx.
}
總體來說,委托是一種強大的機制,可以簡化代碼并提高代碼的可維護性。通過委托,可以將通用的行為抽取到委托類中,然后在需要的地方使用委托來代理這些行為。