Delegated Properties

Delegated Properties

There are certain common kinds of properties, that, though we can implement them manually every time we need them, would be very nice to implement once and for all, and put into a library. Examples include

  • lazy properties: the value gets computed only upon first access,
  • observable properties: listeners get notified about changes to this property,
  • storing properties in a map, not in separate field each.

To cover these (and other) cases, Kotlin supports delegated properties:

class Example {
    var p: String by Delegate()
}

The syntax is: val/var <property name>: <Type> by <expression>. The expression after by is the delegate, because get() (and set()) corresponding to the property will be delegated to its getValue() and setVal