Created
December 26, 2024 03:49
-
-
Save tmxdyf/e9dee721d54978cd2685da1eee64ba1a to your computer and use it in GitHub Desktop.
自定义带接收者的Lazy
This file contains hidden or 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.properties.ReadOnlyProperty | |
| import kotlin.reflect.KProperty | |
| private val UNINITIALIZED_VALUE = Any() | |
| /** | |
| * | |
| * @author CY 2024-12-25 | |
| */ | |
| class ReceiverLazy<in T, out V>(private val initializer: T.() -> V) : LazyProperty<T, V> { | |
| private val lock = Any() | |
| private var _value: Any? = UNINITIALIZED_VALUE | |
| override fun getValue(thisRef: T, property: KProperty<*>): V { | |
| val v1 = _value | |
| if (v1 != UNINITIALIZED_VALUE) { | |
| return v1 as V | |
| } | |
| return synchronized(lock) { | |
| val v2 = _value | |
| if (v2 != UNINITIALIZED_VALUE) { | |
| v2 as V | |
| } else { | |
| val typedValue = initializer(thisRef) | |
| _value = typedValue | |
| typedValue | |
| } | |
| } | |
| } | |
| } | |
| interface LazyProperty<in T, out V> : ReadOnlyProperty<T, V> | |
| /** | |
| * Receiver lazy | |
| * | |
| * @param T | |
| * @param V | |
| * @param initializer | |
| * @receiver | |
| * @return | |
| */ | |
| fun <T, V> receiverLazy(initializer: T.() -> V): LazyProperty<T, V> = | |
| ReceiverLazy(initializer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment