Sobes.tech
Junior — Middle

Explain the principle of delegated properties in Kotlin.

sobes.tech AI

Answer from AI

In Kotlin, delegated properties allow redirecting read and write operations of a property to another object — the delegate. This simplifies reusing 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 is calculated and printed here
    println(lazyValue) // The value is 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 a map, etc.

Explain the principle of delegated properties in… - sobes.tech