Last active
October 4, 2021 13:20
-
-
Save zsqw123/3b3ba256edcbe0857a4e8238c2f8100e to your computer and use it in GitHub Desktop.
kotlin 扩展属性 set 方法无法使用 feild 处理办法
This file contains 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 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) | |
} |
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
example Code: