티스토리 뷰
Without property delegation
class UserSettings(
private val prefs: SharedPreferences
) {
var name: String
get() = prefs.getString("name", "") ?: ""
set(value) {
prefs.edit {
putString("name", value)
}
}
var age: Int
get() = prefs.getInt("age", 0) ?:0
set(value) {
prefs.edit {
putInt("name", value)
}
}
}
Using delegate looks much cleaner
class UserSettings(
private val prefs: SharedPreferences
) {
var name by prefs.string()
var age by prefs.int()
}
Add generic delegate
class SharedPreferencesDelegate<T>(
private val delegate: SharedPreferences,
private val key: String? = null,
private val defaultValue: T,
private val getter: SharedPreferences.(String, T) -> T?,
private val setter: SharedPreferences.Editor.(String, T) -> Unit
) : ReadWriteProperty<Any, T> {
override fun getValue(thisRef: Any, property: KProperty<*>): T {
return delegate.getter(key ?: property.name, defaultValue) ?: defaultValue
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
delegate.edit {
setter(key ?: property.name, value)
}
}
}
Exensions for supported type
fun SharedPreferences.string(
key: String? = null,
defaultValue: String = ""
) = SharedPreferencesDelegate(
delegate = this,
key = key,
defaultValue = defaultValue,
getter = SharedPreferences::getString,
setter = SharedPreferences.Editor::putString
)
fun SharedPreferences.int(
key: String? = null,
defaultValue: Int = 0
) = SharedPreferencesDelegate(
delegate = this,
key = key,
defaultValue = defaultValue,
getter = SharedPreferences::getInt,
setter = SharedPreferences.Editor::putInt
)
fun SharedPreferences.long(
key: String? = null,
defaultValue: Long = 0L
) = SharedPreferencesDelegate(
delegate = this,
key = key,
defaultValue = defaultValue,
getter = SharedPreferences::getLong,
setter = SharedPreferences.Editor::putLong
)
fun SharedPreferences.float(
key: String? = null,
defaultValue: Float = 0f
) = SharedPreferencesDelegate(
delegate = this,
key = key,
defaultValue = defaultValue,
getter = SharedPreferences::getFloat,
setter = SharedPreferences.Editor::putFloat
)
fun SharedPreferences.boolean(
key: String? = null,
defaultValue: Boolean = false
) = SharedPreferencesDelegate(
delegate = this,
key = key,
defaultValue = defaultValue,
getter = SharedPreferences::getBoolean,
setter = SharedPreferences.Editor::putBoolean
)
fun SharedPreferences.stringSet(
key: String? = null,
defaultValue: Set<String> = emptySet()
) = SharedPreferencesDelegate(
delegate = this,
key = key,
defaultValue = defaultValue,
getter = SharedPreferences::getStringSet,
setter = SharedPreferences.Editor::putStringSet
)
'Kotlin' 카테고리의 다른 글
Kotlin's Result sealed class (0) | 2022.02.18 |
---|---|
Kotln, Modern Programming Lauage (0) | 2018.12.30 |
댓글