Delegated properties
We've already seen previously in Chapter 3, Classes and Object-Oriented Programming, about classes how Kotlin's by
keyword can be used for class delegation. The same keyword can also be used for property delegation. As the name suggests, this concept allows a property's get
or set
methods to be delegated to another object. First, we’ll learn how to write a delegate, then we’ll see what delegates are included with the standard library.
Let's say we want a property that is lazily initialized, that is, initialized when accessed for the first time. We can use a delegate property for this:
private val str by lazyProperty { "I'm lazily initialized" }
The syntax for a delegate property is the by
keyword, followed by an expression that returns an instance of the ReadOnlyProperty
interface in the case of an immutable property, or the ReadWriteProperty
interface in the case of a mutable property. This is how the interfaces are defined:
public interface ReadOnlyProperty<in R, out...