|The Programmers Guide To Kotlin - Delegated Properties|
|Written by Mike James|
|Monday, 17 December 2018|
Page 1 of 2
Properties are fundamental to objects and languages differ in how sophisticated they are. Kotlin has a very sophisticated property infrastructure including delegated properties where another object is used to provide properties to a range of other classes.
Programmer's Guide To Kotlin
Now Available as a Print Book
You can buy it from: Amazon
Some Chapters Already Available On The Web
Properties are the way data is represented in an object-oriented language. Each class has the responsibility for creating get and set functions to allow the outside world to modify and access the data. Some types of property are more sophisticated than a simple set and get with backing variables.
For example, a property might keep a history of its previous values or it might call registered callbacks when its value changes – observable properties and so on. You can implement these mechanisms on a class-by-class basis but this isn't particularly efficient, and if you want to change the way a property works you will have to go round all of the classes and change them all.
Kotlin provides a way to delegate property implementation to another class. It also allows you to delegate a local variable in a function which isn't a property in the same way:
For example to delegate a property:
and to delegate a local variable:
In this case the delegate is an instance of the class myDelegate. This has to provide a get and set function with a particular signature. The get is:
and the set is:
where thisRef is the object doing the delegating, property is an object that represents the property, value is the value to be set and T is the type of the property. Notice that for a local variable Any will be set to null as there is no object doing the delegating. We also need to add:
to use Kproperty.
So in the case of our myClass example with an Int parameter, myDelegate might be:
where for simplicity of the example, the get returns 1 and the set throws the value away.
If you want to make sure the get and set are correct or want the system to generate stubs simply implement one of the standard interfaces ReadOnlyProperty<R,T> or ReadyWriteProperty<R,T> where R is the type of thisRef and T is the type of the property.
If we try to use the property just defined:
You will see 1 printed. Notice that the system has created an instance of myDelegate to use with myObject. Every time you create an instance of myObject you get a new instance of myDelegate to work with it.
|Last Updated ( Saturday, 26 January 2019 )|