前言
kotlin官網和kotlin教程學習教程的筆記。
這里使用一次委托來實現SharedPreferences的相關方法,用來復習一下委托O(∩_∩)O~
希望大家自己寫一遍試試,感覺不對再看對比下面的代碼,尋找原因。
一、preference委托
class Preference<T>(val key: String, context: Context, val default: T) : ReadWriteProperty<Any?, T> {
val prefs by lazy { context.getSharedPreferences("file", Context.MODE_PRIVATE) }
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putPreference(key, value)
}
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return findPreference(key, default)
}
private fun findPreference(key: String, default: T) = with(prefs) {
val result: Any = when (default) {
is String -> getString(key, default)
is Int -> getInt(key, default)
else -> throw IllegalArgumentException("this type can not be readed")
}
result as T
}
private fun putPreference(key: String, value: T) = with(prefs.edit()) {
when (value) {
is String -> putString(key, value)
is Int -> putInt(key, value)
else -> throw IllegalArgumentException("this type can not be saved")
}
}.commit()
}
二、使用
var id: Int by Preference(ID, this, 0)
三、統一委托使用
我們可能不止有preference的自定義委托,可能還有其他的委托,為了方便統一管理,我們可以這樣。
object CustomDelegate{
fun <T> preference(key: String, context: Context, default: T) = Preference(key, context, default)
}
var id: Int by CustomDelegate.preference(ID, this, 0)
四、后記
至此,kotlin的教程全部結束了,anko的源碼可以多看看,很有好處的~\(≧▽≦)/~