Kotlin 标准库为几种有用的委托提供了工厂方法。
- 延迟属性Lazy
val lazyValue: String by lazy {
println("computed!")
"Hello"
}
fun main() {
println(lazyValue)
println(lazyValue)
}
输出
computed!
Hello
Hello
- 可观察属性 Observable
import kotlin.properties.Delegates
class User {
var name: String by Delegates.observable("<no name>") {
prop, old, new ->
println("$old -> $new")
}
}
fun main() {
val user = User()
user.name = "first"
user.name = "second"
}
输出:
<no name> -> first
first -> second
使用vetoable()取代observable()可以用来截获赋值,返回true表示此次有效,返回false表示此次无效
3. 把属性储存在映射中(忽略)
使用委托实现MMKV存储数值
/**
* @author zyl
* @date 2020/7/16 10:10 AM
*/
class MmkvUtil<T>(val key: String, private val default: T) : ReadWriteProperty<Any?, T> {
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return decode(key, default)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
encode(key, value)
}
private fun <U> decode(key: String, default: U): U = with(MMKV.defaultMMKV()) {
val res = when (default) {
is Int -> decodeInt(key, default)
is Long -> decodeLong(key, default)
is Float -> decodeFloat(key, default)
is Double -> decodeDouble(key, default)
is Boolean -> decodeBool(key, default)
is String -> decodeString(key, default)
is ByteArray -> decodeBytes(key, default)
else -> throw IllegalArgumentException("This type can not be exist mmkv")
}
return@with res as U
}
private fun <U> encode(key: String, value: U) = with(MMKV.defaultMMKV()) {
when (value) {
is Int -> encode(key, value)
is Long -> encode(key, value)
is Float -> encode(key, value)
is Double -> encode(key, value)
is Boolean -> encode(key, value)
is String -> encode(key, value)
is ByteArray -> encode(key, value)
else -> throw IllegalArgumentException("This type can not be saved into mmkv")
}
}
}
使用
val mv by MmkvUtil("key", "")
println("${mv}")
mv = "aaa"
println("${mv}")
mv = "bbb"
println("${mv}")