Skip to content

Instantly share code, notes, and snippets.

@ekursakov
Created October 6, 2016 17:25
Show Gist options
  • Save ekursakov/ecb7610360f8c4a86de4d75cc93ea58c to your computer and use it in GitHub Desktop.
Save ekursakov/ecb7610360f8c4a86de4d75cc93ea58c to your computer and use it in GitHub Desktop.
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun SharedPreferences.boolProperty(key: String, defaultValue: Boolean)
= preferenceProperty(this, { getBoolean(key, defaultValue) }, { putBoolean(key, it) })
fun SharedPreferences.floatProperty(key: String, defaultValue: Float)
= preferenceProperty(this, { getFloat(key, defaultValue) }, { putFloat(key, it) })
fun SharedPreferences.intProperty(key: String, defaultValue: Int)
= preferenceProperty(this, { getInt(key, defaultValue) }, { putInt(key, it) })
fun SharedPreferences.longProperty(key: String, defaultValue: Long)
= preferenceProperty(this, { getLong(key, defaultValue) }, { putLong(key, it) })
fun SharedPreferences.stringProperty(key: String, defaultValue: String)
= preferenceProperty(this, { getString(key, defaultValue) }, { putString(key, it) })
fun SharedPreferences.stringSetProperty(key: String, defaultValues: Set<String>)
= preferenceProperty(this, { getStringSet(key, defaultValues) }, { putStringSet(key, it) })
private inline fun <T> preferenceProperty(
sharedPreferences: SharedPreferences,
crossinline getter: SharedPreferences.() -> T,
crossinline setter: SharedPreferences.Editor.(T) -> SharedPreferences.Editor
): ReadWriteProperty<Any?, T> {
return object : ReadWriteProperty<Any?, T> {
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
sharedPreferences.edit().setter(value).apply()
}
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return sharedPreferences.getter()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment