🐦 Kotlin Intermediate

What is property delegation in Kotlin?

Answer

Property delegation allows you to delegate the getter and setter logic of a property to another object using the by keyword. The delegate object must implement getValue() (and setValue() for mutable properties). Kotlin's standard library provides built-in delegates: lazy (lazy initialization), Delegates.observable() (callback on change), Delegates.vetoable() (conditionally reject changes), and map (store properties in a map). You can create custom delegates by implementing the ReadOnlyProperty or ReadWriteProperty interfaces, enabling reusable property behavior like validation or logging.