Kotlin Delegate in Android (Part 1)

Tram Ho

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:

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:

So a delegates is a class with two methods: getting and setting for properties. To give it some information to create a new Delegate

It is equivalent to:

::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

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo