Save and load objects from SharedPreferences in a faster and simpler way with Kotlin Extensions.

This project is a "Kotlin extensions" version of SharedPrefsUtils

Version 1.x

  • September, 2019 - Kotlin version

Getting started

The first step is to include SharedPrefsUtils-ktx into your project, for example, as a Gradle compile dependency:

implementation 'com.github.guilhe:SharedPrefsUtils-ktx:${LATEST_VERSION}'

Maven Central Download

Sample usage

Get a hold of SharedPreferences instance to use the extensions put and get:

lateinit var prefs: SharedPreferences
prefs = appContext.getSharedPreferences("test", Context.MODE_PRIVATE)

To save and load primitive types:

prefs.put("key", 1)
val a = prefs.get("key",, 1)

To save and load object types:

val list = mutableListOf<Int>()
prefs.put("key", list)
list = prefs.get("key", object : TypeToken<List<Int>>() {}, mutableListOf()))

When not using primitive types you should use TypeToken instead of, for example:

    fun getObjectWithType() {
        val list = ArrayList<MyObjectType>()
        list.add(MyObjectType("string", 1, true))
        prefs.put("key", list)

        assertEquals(list, prefs.get("key", object : TypeToken<List<MyObjectType>>() {}, ArrayList()))
        assertNotEquals(list, prefs.get("key",, ArrayList<MyObjectType>()))

    fun getObjectWithType2() {
        val list = ArrayList<Int>()
        prefs.put("key", list)

        assertEquals(list, prefs.get("key", object : TypeToken<List<Int>>() {}, ArrayList()))
        assertNotEquals(list, prefs.get("key",, ArrayList<Int>()))

    @Parcelize data class MyObjectType(val fieldA: String, val fieldB: Int, val fieldC: Boolean) : Parcelable

Both tests will ran to completion.

Regarding assertNotEquals(list, prefs.get("key",, ArrayList<Int>())) being true, I guess it's related with the fact that public <T> T fromJson(JsonReader reader, Type typeOfT){} method from (line 886) is type unsafe:
"Since Type is not parameterized by T, this method is type unsafe and should be used carefully".
That's why I believe I'm getting List<Double> instead of List<Integer>.


prefs.put(prefs, "key", 1)
prefs.get(prefs, "key",, false)

Will throw JsonParseException.


Additional binaries and dependency information for can be found at


Bugs and Feedback

For bugs, questions and discussions please use the Github Issues.