Skip to content

Instantly share code, notes, and snippets.

@mrenouf
Last active December 9, 2025 04:13
Show Gist options
  • Select an option

  • Save mrenouf/690d16999729cd1b482af2430d17ad80 to your computer and use it in GitHub Desktop.

Select an option

Save mrenouf/690d16999729cd1b482af2430d17ad80 to your computer and use it in GitHub Desktop.
MutableLazy
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