Skip to content

Instantly share code, notes, and snippets.

@rakshakhegde
Last active October 30, 2017 17:39
Show Gist options
  • Save rakshakhegde/92330c323bf4aa5e4bb7cbe54a01a2ae to your computer and use it in GitHub Desktop.
Save rakshakhegde/92330c323bf4aa5e4bb7cbe54a01a2ae to your computer and use it in GitHub Desktop.
Handy Kotlin Android Utility to store key-value pairs in SharedPreferences
/**
* Handy utility to store key-value pairs in SharedPreferences
* without the hassle of 'apply'
*
* Usage (in Activity/Fragment):
* ```
* defaultSharedPreferences.apply("ACCESS_TOKEN" to "accessToken", "NAME" to "name")
* ```
*
* @param pairs Pairs of key and value to store
*/
fun SharedPreferences.apply(vararg pairs: Pair<String, String>) {
edit().apply {
pairs.forEach { putString(it.first, it.second) }
}.apply()
}
@ralph-bergmann
Copy link

I changed it a little bit :-)

fun SharedPreferences.apply(vararg pairs: Pair<String, Any?>) {
    edit().apply {
        pairs.forEach {
            when (it.second) {
                null -> remove(it.first)
                is Boolean -> putBoolean(it.first, it.second as Boolean)
                is Float -> putFloat(it.first, it.second as Float)
                is Int -> putInt(it.first, it.second as Int)
                is Long -> putLong(it.first, it.second as Long)
                is String -> putString(it.first, it.second as String)
            }
        }
    }.apply()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment