Junior — Middle
Selgitage Kotlin programmeerimiskeeles delegeeritud omaduste tööpõhimõtet.
sobes.tech AI
Vastus AI-lt
In Kotlin, delegated properties allow redirecting read and write operations of a property to another object — the delegate. This simplifies the reuse of access logic.
Syntax:
var propertyName: Type by delegate
For example, the standard lazy delegate initializes the value upon first access:
val lazyValue: String by lazy {
println("Calculating value")
"Hello, Kotlin!"
}
fun main() {
println(lazyValue) // The value will be calculated and printed here
println(lazyValue) // The value will be retrieved from cache here
}
You can create your own delegates by implementing the ReadOnlyProperty or ReadWriteProperty interfaces. Delegates are useful for implementing properties with deferred initialization, change observation, storage in maps, etc.