Skip to content

Instantly share code, notes, and snippets.

@toddway
Created July 24, 2017 18:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toddway/14527bfd94d132c3b1998e38ba68d6ff to your computer and use it in GitHub Desktop.
Save toddway/14527bfd94d132c3b1998e38ba68d6ff to your computer and use it in GitHub Desktop.
Kotlin property delegates for SharedPreferences
val preferences : SharedPreferences = ...
//Old way...
val MY_BOOLEAN_PREF = "myBooleanPref"
val MY_STRING_PREF = "myStringPref"
fun oldSharedPreferenceExample() {
//set
val editor = preferences.edit()
editor.putBoolean(MY_BOOLEAN_PREF, true)
editor.putString(MY_STRING_PREF, "this is some text")
editor.apply()
//get
val bool = preferences.getBoolean(MY_BOOLEAN_PREF, false)
val text = preferences.getString(MY_STRING_PREF, "")
}
//New way...
var SharedPreferences.myBooleanPref by Pref(false)
var SharedPreferences.myStringPref by Pref("")
fun newSharedPreferenceExample() {
//set
preferences.myBooleanPref = true
preferences.myStringPref = "this is some text"
//get
val bool = preferences.myBooleanPref
val text = preferences.myStringPref
}
import android.content.SharedPreferences
import kotlin.reflect.KProperty
class Pref<T>(val default : T) {
operator fun getValue(prefs: SharedPreferences, property: KProperty<*>): T = with(prefs) {
val name = property.name
@Suppress("UNCHECKED_CAST")
val value: Any = when (default) {
is Long -> getLong(name, default)
is String -> getString(name, default)
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is Float -> getFloat(name, default)
is Set<*> -> getStringSet(name, default as Set<String>)
else -> throw IllegalArgumentException("$default is not a valid Pref type")
}
@Suppress("UNCHECKED_CAST")
return value as T
}
operator fun setValue(prefs: SharedPreferences, property: KProperty<*>, value: T) = with(prefs.edit()) {
val name = property.name
@Suppress("UNCHECKED_CAST")
when (value) {
is Long -> putLong(name, value)
is String -> putString(name, value)
is Int -> putInt(name, value)
is Boolean -> putBoolean(name, value)
is Float -> putFloat(name, value)
is Set<*> -> putStringSet(name, value as Set<String>)
else -> throw IllegalArgumentException("$value is not a valid Pref type")
}.apply()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment