Last active
December 9, 2025 04:13
-
-
Save mrenouf/690d16999729cd1b482af2430d17ad80 to your computer and use it in GitHub Desktop.
MutableLazy
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
| package com.bitgrind.scrabble.ext | |
| import kotlin.concurrent.atomics.AtomicReference | |
| import kotlin.concurrent.atomics.ExperimentalAtomicApi | |
| import kotlin.reflect.KProperty | |
| fun <T : Any> mutableLazy(initializer: () -> T) = MutableLazy(initializer) | |
| /** | |
| * A PUBLICATION-style atomic lazy that’s also mutable. | |
| * | |
| * The initializer *may* be called multiple times, but | |
| * only the first result is stored and is returned to | |
| * all callers. | |
| */ | |
| @OptIn(ExperimentalAtomicApi::class) | |
| class MutableLazy<T : Any>(val initializer: () -> T) { | |
| private val valueRef: AtomicReference<T?> = AtomicReference(null) | |
| @OptIn(ExperimentalAtomicApi::class) | |
| operator fun getValue(thisRef: Any?, property: KProperty<*>): T { | |
| return valueRef.load() ?: let { | |
| val initValue = initializer() | |
| valueRef.compareAndExchange(null, initValue) ?: initValue | |
| } | |
| } | |
| operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { | |
| valueRef.store(value) | |
| } | |
| fun clear() { | |
| valueRef.store(null) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment