Leverage the power of Delegate in the development of Android
Kotlin is a modern language with many great features to make application development more attractive and more interesting experience. One of those features is Delegated Properties. In this article, we will see how and how Delegate can make our lives easier in the development of Android.
The parts I go through are:
1 – Basic
2 – For example
Fragment arguments
SharedPreferences delegates
View delegates
3 – Summary.
1 – Basic.
First of all, what is Delegate and how does it work? . Good thing about it is there is a certain kind of magic potential nhỉ But actually it's not that complicated.
Delegate is essentially a class that provides value to the property and handles its changes. This allows us to move, delegate, getter – setter logic from its properties into a separate class and reuse this logic.
We want a parameter of type String to always be trimmed (trim ()) ie with leading and trailing spaces removed. We can do this with the setter property as follows:
1 2 3 4 5 6 7 8 | class Example { var param: String = "" set(value) { field = value.trim() } } |
If you have any questions about the syntax above. You can review it at the following link https://kotlinlang.org/docs/reference/properties.html
Now, what if we want to reuse this feature in some other classes? This is where the delegates handle:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class TrimDelegate : ReadWriteProperty<Any?, String> { private var trimmedValue: String = "" override fun getValue( thisRef: Any?, property: KProperty<*> ): String { return trimmedValue } override fun setValue( thisRef: Any?, property: KProperty<*>, value: String ) { trimmedValue = value.trim() } } |
So a delegates is a class with two methods: getting and setting for properties. To give it some information to create a new Delegate
1 2 3 4 | class Example { var param: String by TrimDelegate() } |
It is equivalent to:
1 2 3 4 5 6 7 8 9 10 | class Example { private val delegate = TrimDelegate() var param: String get() = delegate.getValue(this, ::param) set(value) { delegate.setValue(this, ::param, value) } } |
::param
is the operator that returns an instance of KProperty class for attribute.
As you can see above, there's nothing mysterious about Delegates. Though simple, it can be very helpful for you while developing Android. In this section, I explain to you about how Delegate runs inside. The following part I will make examples of Fragment arguments – SharedPreferences delegates – View delegates. See you later
Reference: https://proandroiddev.com/kotlin-delegates-in-android-1ab0a715762d