Skip to content

Instantly share code, notes, and snippets.

@ethauvin
Last active January 18, 2018 14:04
Show Gist options
  • Save ethauvin/9eafa3a94afef6b6a50af07fdc940abf to your computer and use it in GitHub Desktop.
Save ethauvin/9eafa3a94afef6b6a50af07fdc940abf to your computer and use it in GitHub Desktop.
Android SharedPreferences shorthands for Kotlin
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
fun Context.getDefaultSharedPreferences(): SharedPreferences {
return PreferenceManager.getDefaultSharedPreferences(this)
}
fun SharedPreferences.clear() {
edit().clear().apply()
}
fun SharedPreferences.put(key: String, value: Any) {
when (value) {
is String -> edit().putString(key, value).apply()
is Float -> edit().putFloat(key, value).apply()
is Int -> edit().putInt(key, value).apply()
is Boolean -> edit().putBoolean(key, value).apply()
is Long -> edit().putLong(key, value).apply()
is Set<*> -> {
if (value.all { it is String }) {
edit().putStringSet(key, value as Set<String>)
}
}
}
}
fun SharedPreferences.put(vararg pairs: Pair<String, String>) {
edit().apply {
pairs.forEach {
putString(it.first, it.second)
}
}.apply()
}
fun SharedPreferences.remove(key: String) {
edit().remove(key).apply()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment