Created
October 6, 2016 17:25
-
-
Save ekursakov/ecb7610360f8c4a86de4d75cc93ea58c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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