Delegating Variables and Properties

In the examples so far, we focused on delegation at the class level. You may delegate get and set access to properties of objects and local variables too.

When you read a property or a local variable, internally Kotlin calls a getValue() function. Likewise, when you update a property or a variable, it calls a setValue() function. By providing as delegate an object with these two methods, you may intercept calls to read and write local variables and objects’ properties.

Delegating Variables

You can intercept access, both read and write, to local variables and alter what is returned and where and how the data is stored. To illustrate this facility, let’s create a custom delegate to intercept access of String ...

Get Programming Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.