Skip to content

Instantly share code, notes, and snippets.

@zhgqthomas
Last active August 10, 2018 22:05
Show Gist options
  • Save zhgqthomas/3e81afa0140fbab19c08 to your computer and use it in GitHub Desktop.
Save zhgqthomas/3e81afa0140fbab19c08 to your computer and use it in GitHub Desktop.
SharedPreference Delegate extension (Kotlin)
object DelegatesExt {
fun <T : Any> preference(context: Context, name: String, default: T)
= Preference(context, name, default)
}
class Preference<T>(val context: Context, val name: String,
val default: T) : ReadWriteProperty<Any?, T> {
companion object {
val PREF_NAME: String = "chameleon"
}
val prefs by lazy { context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) }
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return getPreference(name, default)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putPreference(name, default)
}
@Suppress("UNCHECKED_CAST")
private fun <U> getPreference(name: String, default: U): U = with(prefs) {
val res: 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)
else -> throw IllegalArgumentException("This type can be saved into Preferences")
}
res as U
}
private fun <U> putPreference(name: String, value: U) = with(prefs.edit()) {
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)
else -> throw IllegalArgumentException("This type can be saved into Preferences")
}.apply()
}
}
@skrugly
Copy link

skrugly commented Apr 17, 2016

Bug in the 20 line. should be: putPreference(name, value)

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