Skip to content

Instantly share code, notes, and snippets.

@dpolishuk
Created November 19, 2015 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpolishuk/6f228d67bdaec1b84c9e to your computer and use it in GitHub Desktop.
Save dpolishuk/6f228d67bdaec1b84c9e to your computer and use it in GitHub Desktop.
MyPreference.kt
fun SharedPreferences.edit(func: SharedPreferences.Editor.() -> Array<Pair<String, Any>>) : SharedPreferences.Editor {
val editor = edit()
val pairs = editor.func()
for ((key, value) in pairs) {
when (value) {
is String -> editor.putString(key, value)
is Set<*> -> {
if (!value.all { it is String }) {
throw IllegalArgumentException("Only Set<String> is supported")
}
editor.putStringSet(key, value as Set<String>)
}
is Int -> editor.putInt(key, value)
is Long -> editor.putLong(key, value)
is Float -> editor.putFloat(key, value)
is Boolean -> editor.putBoolean(key, value)
else -> throw IllegalArgumentException("Unsupported value type: ${value.javaClass}")
}
}
if (pairs.size > 0) {
editor.apply()
}
return editor
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment