Skip to content

Instantly share code, notes, and snippets.

@zsqw123
Last active October 4, 2021 13:20
Embed
What would you like to do?
kotlin 扩展属性 set 方法无法使用 feild 处理办法
import kotlin.reflect.KProperty
/**
* this will be used:
* 1. before getValue return.
* 2. before setValue to change the value.
*/
typealias ValueIntercepter<ValType> = (originValue: ValType) -> ValType
fun <ValType : Any?> exVar(
defVal: ValType, getter: ValueIntercepter<ValType> = { it }, setter: ValueIntercepter<ValType> = { it },
) = ExtensionValueDelegates(defVal, getter, setter)
class ExtensionValueDelegates<ValType : Any?>(
val defVal: ValType, val getter: ValueIntercepter<ValType>, val setter: ValueIntercepter<ValType>,
) {
var field: Any? = INVALIDATE
companion object {
object INVALIDATE
}
}
inline operator fun <This : Any, reified ValType> ExtensionValueDelegates<ValType>.getValue(thisRef: This, property: KProperty<*>): ValType {
val realV: ValType =
if (field != ExtensionValueDelegates.Companion.INVALIDATE) field as ValType
else defVal
return getter(realV)
}
inline operator fun <This : Any, reified ValType> ExtensionValueDelegates<ValType>.setValue(thisRef: This, property: KProperty<*>, value: ValType) {
field = setter(value)
}
@zsqw123
Copy link
Author

zsqw123 commented Oct 4, 2021

maybe sometimes we need null delegates, it's ok!

var Awa.e: String? by exVar(null)

fun main() {
    val awa = Awa()
    println(awa.e)
    awa.e = "sdjskd"
    println(awa.e)
    awa.e = null
    println(awa.e)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment