Attribute delegation of Kotlin: Android assignment (KAD 15) and kotlinandroid without context

Source: Internet
Author: User

Attribute delegation of Kotlin: Android assignment (KAD 15) and kotlinandroid without context

 

By Antonio Leiva

Time: Mar 9 and 2017

Link: https://antonioleiva.com/property-delegation-kotlin/

 

 

As we have read in the previous article, attributes require default values, and attributes cannot be declared without being assigned values.

 

 

Because you want to store the view to the attribute, this creates a problem. During object creation, the value assignment code is executed, and you cannot access this content at this time.

 

 

What can you do?

 

 

Property delegation: Delegate the property value to another object.

 

 

 

The property delegate uses another object, which can call get and set (if var is used) to return results.

 

Currently, we cannot control the creation of many objects, such as the Android framework. In many cases, this delegate will save our lives.

 

I will show you three examples, which I think are very useful in Android.

 

Set view to attribute

 

In this example, we use delegation with two options, and the use of null is forbidden (if you can avoid it, some things are not recommended ).

 

This is my favorite because it forces you to use var for immutable and insecure attributes.

 

The reserved word lateinit indicates that the attribute cannot be blank, but we still have no final value:

1 lateinit var textView:TextView

 

In onCreate, we can assign a value to final:

1 setContentView(R.layout.activity_main)2 textView = findView(R.id.welcomeMessage)3 toast(textView.text)

 

Although it is the same operation as delegate notNull and is classified as the first favorite, it is not the real delegate.

 

The second option is more elegant. It is composed of Lazy delegates until the attribute is called for the first time, and the relevant code is not executed:

1 val textView by lazy { findView(R.id.welcomeMessage) }

 

FindView cannot run until the get of textView is called for the first time. Because you cannot mistakenly modify its value, it is safer, and it does not force us to remember to set it after setContentView.

 

At this moment, we will do:

 

1 toast(textView.text)

 

 

This line of code will be executed in lazy format.

 

As you can see, delegation is represented by reserved words.

 

Let's look at another example.

 

Change Notification Adapter

 

In the adapter, we have the items attribute, which is updated every time the adapter is automatically started.

 

1 var items: List by Delegates.observable(emptyList()) {2     _, _, _ -> notifyDataSetChanged()3 }

 

It simply sets the initial value and calls the defined function after each change.

 

 

In this case, I only call notifyDataSetChanged. However, as you can see, the new and old values received by the function, so technically you can check what the changes are and only update the differences.

 

If you are interested in this example, I will describe it more extensively in another article.

 

Dagger Diagram for declaring the Lazy method

 

 

 

 

This is another very useful situation I have found.

 

 

ReturnLazy, You can use it to declare the component of the application during the attribute declaration:

 

1 val component: AppComponent by lazy { 2     DaggerAppComponent3             .builder()4             .appModule(AppModule(this))5             .build() 6 }

 

 

In this method, you do not need to use lateinit, and the attribute is immutable.

 

If subcomponents is used in the Activity, you can do the same thing:

1 class HomeActivity : AppCompatActivity(), HomePresenter.View {2     val component by lazy { app.component.plus(HomeModule(this)) }3     ...4 }

 

New Kotlin 1.1: partial delegation attribute

 

We have seen how to use delegation to provide additional capabilities for class attributes. For example, does lazy really help variables? Kotlin lacks this feature.

 

Now, with the partial delegate attribute, we do:

 

 1 fun testLocalDelegation() { 2     val database by lazy { createDatabase() } 3     val cache by lazy { createMemoryCache() } 4  5     if (mustUseDatabase()) { 6         database.use { ... } 7     } else { 8         cache.use { ... } 9     }10 }

 

 

Although this example can be solved without lazy delegation, it helps to understand these concepts.

 

There are several "bulky" objects that may or will not be used. By using lazy,We can postpone their instantiation until we are sure we want to use them.

 

 

When used for the first time, the code in curly braces is executed and cached for future use.

 

Conclusion

 

 

Attribute delegation will help you make attributes more powerful, simpler, and reusable.

 

 

Here we only see the standard attributes of the Kotlin library, and you can create your own attributes.

 

For example, in this book, I have implemented the storage and retrieval of data from SharedPreference.

 

If you want to learn more about the content and are fluent enough to create your own Android app, I suggest you get this free guide to learn how to create your first project, or you can directly obtain this book and learn how to create a complete application from scratch.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.