Created
November 5, 2021 08:51
-
-
Save legendmohe/522fb3ff486d7aa771c2b1b58638adf4 to your computer and use it in GitHub Desktop.
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
/** | |
* 不为空的时候才给lazy赋值 | |
*/ | |
public fun <T> lazyNotNull(initializer: () -> T?): Lazy<T?> = SynchronizedLazyNotNullImpl(initializer) | |
internal object UNINITIALIZED_VALUE | |
private class SynchronizedLazyNotNullImpl<out T>(initializer: () -> T?, lock: Any? = null) : Lazy<T?>, | |
java.io.Serializable { | |
private var initializer: (() -> T?)? = initializer | |
@Volatile | |
private var _value: Any? = UNINITIALIZED_VALUE | |
// final field is required to enable safe publication of constructed instance | |
private val lock = lock ?: this | |
override val value: T? | |
get() { | |
val _v1 = _value | |
if (_v1 !== UNINITIALIZED_VALUE) { | |
@Suppress("UNCHECKED_CAST") | |
return _v1 as T | |
} | |
return synchronized(lock) { | |
val _v2 = _value | |
if (_v2 !== UNINITIALIZED_VALUE) { | |
@Suppress("UNCHECKED_CAST") (_v2 as T) | |
} else { | |
val typedValue = initializer!!() | |
if (typedValue != null) { | |
_value = typedValue | |
initializer = null | |
typedValue | |
} else { | |
null | |
} | |
} | |
} | |
} | |
override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE | |
override fun toString(): String = | |
if (isInitialized()) value.toString() else "Lazy value not initialized yet." | |
private fun writeReplace(): Any = InitializedLazyImpl(value) | |
} | |
internal class InitializedLazyImpl<out T>(override val value: T) : Lazy<T>, java.io.Serializable { | |
override fun isInitialized(): Boolean = true | |
override fun toString(): String = value.toString() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment