Properties jsou většinou představeny odpovídajícím polem ve třídě (např. val x: Int). Mohou ale být i delegovány. Jejich hodnota je získána od toho, na koho byla tato práce přenesena (delegována). Jinak řečeno getValue a setValue funce zajišťuje delegovaný kód. Delegované vlastnosti se používají deklarováním vlastnosti a delegáta, kterého používají.
Příklad 1
class Example {
var property: Int by Delegate()
}
class Delegate {
var random = Random(0)
operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
println("$javaClass - getting random value | thisRef -> $thisRef, property -> $property")
return random.nextInt()
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
println("$javaClass creating new random with seed value: $value | thisRef -> $thisRef, property -> $property")
random = Random(value)
}
}
fun main() {
val e = Example()
println(e.property)
e.property = 10
println(e.property)
}
Výsledek
class cz.vitfo.Delegate - getting random value | thisRef -> cz.vitfo.Example@762efe5d, property -> var cz.vitfo.Example.property: kotlin.Int -1934310868 class cz.vitfo.Delegate creating new random with seed value: 10 | thisRef -> cz.vitfo.Example@762efe5d, property -> var cz.vitfo.Example.property: kotlin.Int class cz.vitfo.Delegate - getting random value | thisRef -> cz.vitfo.Example@762efe5d, property -> var cz.vitfo.Example.property: kotlin.Int -129340023
Příklad 2
class Example2 {
var nameV2: String = "Name version 2"
@Deprecated("Use nameV2")
var name: String by this::nameV2
}
fun main() {
val e2 = Example2()
println(e2.name)
println(e2.nameV2)
}
Výsledek
Name version 2 Name version 2
Zdroje: