Let’s talk about Android SharedPreferences. How Kotlin language can helps us to improve it? The first thing that comes to mind, is custom getter and setter:

This move is functional, not so gracefully. Let’s take a look to delegates:

Now we can define any variables through this delegate. For example:

But in this case we have two not so pleasant moments: we can’t change default value and SharedPreferences key always be same as property name. Time to upstairs to next level!

Now we can define any property this way (defValue parameter can be skipped):

And last upgrade. We can extract all delegates to separate file and using them in any project class:

Using:

 

Leave a Reply

Close Menu