SharedPreferences — Made easy with Kotlin generics & extensions

Tuyến Vũ
naxam-blogs
Published in
2 min readMar 25, 2018

--

Being a C# developer for more than 6 years, I really loves its Generics and Extensions feature. I have looked for the same feature on Java while working on Android project, but it isn’t quite the same until I do Kotlin.

In this post, I would like to share how I leverage Kotlin Generics and Extensions to simplify the way we work with SharedPreferences on Android.

Default feature

By default, SharedPreferences class provides us a lot of methods to work with different data types

I don’t really like this way because we have to use the right method for our preference based on its data type.

Generics and Extensions approach

Generics — rescue us from defining multiple methods for multiple data types

Extensions — allows us to call static helper methods like instance methods

Let’s use generics and extensionsto simplify SharedPreferences get/put methods.

That’s it, you now could work with SharedPreferences without remembering exactly getXXX/putXXX, just simply

//To get a preference
val myPreference = sharedPreferences.get("my-preference", "my default value")
//To save a preference
sharedPreferences.put("my-preference", "my value")

Drawback

The approach isn’t really optimal because we could accidentally put any data type to SharedPreferences, and the helper method doesn’t do anything in case data type doesn’t match the data type allowed to save to SharedPreferences.

It is abnormal, but might be the case. The simplest solution is to serialize non-support data type into string on saving, then deserialize on getting.

Hope the post will help you a little to simplify your way when working with SharedPreferences and know another use of Kotlin Extensions and Generics.

--

--