android / android-ktx

A set of Kotlin extensions for Android app development.
https://android.github.io/android-ktx/core-ktx/
7.48k stars 564 forks source link

Feature suggestion: SharedPreferences.putAll keys and values #153

Open jczerski opened 6 years ago

jczerski commented 6 years ago

To my mind it would be nice to have some extension for setting many items to the SharedPreferences, something like this:

prefs.putAll("key0" to 2,
                "key1" to "text",
                "key2" to true,
                "key3" to null)

which does

fun SharedPreferences.putAll(vararg pairs: Pair<String, *>) {
    edit {
        pairs.forEach { (key, value) ->
            when (value) {
                is String -> putString(key, value)
                is Set<*> -> putStringSet(key, value as? Set<String>?)
                is Boolean -> putBoolean(key, value)
                is Float -> putFloat(key, value)
                is Int -> putInt(key, value)
                is Long -> putLong(key, value)
                null -> remove(key)
            }
        }
    }
}

Regards, Jack

JakeWharton commented 6 years ago

Does this really add much value? It causes allocation of varags and pairs for something that isn't much less verbose than the existing edit-with-lambda approach. I'd rather figure out how to make the actions on the editor simpler if possible than something like this.

jczerski commented 6 years ago

You are right, this is not the optimal solution. At the same time, pasting data due to their type is exhausting.

Regards, Jack

f2prateek commented 6 years ago

Instead you could have something an extension function on SharedPreferences.Editorput(key: String, val: Any?). This would do the type switch internally, with some special cases:

JakeWharton commented 6 years ago

We'd do overloads. No need to switch.

On Mon, Feb 5, 2018, 6:56 PM Prateek Srivastava notifications@github.com wrote:

Instead you could have something an extension function on SharedPreferences.Editor —put(key: String, val: Any?). This would do the type switch internally, with some special cases:

  • null -> deletes instead of setting the key
  • non-SharedPreferences supported type -> throws an exception.

— You are receiving this because you commented.

Reply to this email directly, view it on GitHub https://github.com/android/android-ktx/issues/153#issuecomment-363262079, or mute the thread https://github.com/notifications/unsubscribe-auth/AAEEEWTWNlfflftiVSL7Vb-tE4BePrg_ks5tR5UggaJpZM4R6Ph6 .

JakeWharton commented 6 years ago

And delete is already remove("key") which is hard to improve upon.