Property delegation
Kotlin allows not only class delegation, but also property delegation. In this section, we are going to find out what delegated properties are, review property delegates from the Kotlin standard library, and learn how to create and use custom property delegates.
What are delegated properties?
Let's start with an explanation of what property delegates are. Here is an example of the use of property delegation:
class User(val name: String, val surname: String) var user: User by UserDelegate() // 1 println(user.name) user = User("Marcin","Moskala")
- We are delegating the
user
property to an instance ofUserDelegate
(which is created by the constructor).
Property delegation is similar to class delegation. We delegate to an object using the same keyword (by
). Each call to a property (set
/get
) will be delegated to another object (UserDelegate
). This way, we can reuse the same behavior for multiple properties, for example, setting a property value only when some...