Skip to content

Instantly share code, notes, and snippets.

@makeevrserg
Created October 22, 2025 06:47
Show Gist options
  • Select an option

  • Save makeevrserg/2687b1a2fec7bd39aae22b489cc34f9d to your computer and use it in GitHub Desktop.

Select an option

Save makeevrserg/2687b1a2fec7bd39aae22b489cc34f9d to your computer and use it in GitHub Desktop.
MutableLazy
package ru.astrainteractive.klibs.kstorage.threading
import kotlinx.atomicfu.atomic
import kotlin.reflect.KProperty
/**
* A thread-safe, mutable variant of [Lazy] for Kotlin Multiplatform.
*
* The value is initialized on first access using [initializer] and can be reassigned later.
* Safe for concurrent access across platforms (JVM, JS, Native).
*/
internal class MutableLazy<T>(private val initializer: () -> T) : Lazy<T> {
object UNINITIALIZED
private val _value = atomic<Any?>(UNINITIALIZED)
override var value: T
get() {
val current = _value.value
if (current !== UNINITIALIZED) {
@Suppress("UNCHECKED_CAST")
return current as T
}
val newValue = initializer.invoke()
if (_value.compareAndSet(UNINITIALIZED, newValue)) {
return newValue
}
@Suppress("UNCHECKED_CAST")
return _value.value as T
}
set(newValue) {
_value.value = newValue
}
override fun isInitialized(): Boolean {
return _value.value != UNINITIALIZED
}
operator fun getValue(thisRef: Nothing?, property: KProperty<*>): T = value
operator fun setValue(thisRef: Nothing?, property: KProperty<*>, newValue: T) {
value = newValue
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value
operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: T) {
value = newValue
}
}
/**
* Creates a thread-safe [MutableLazy] instance with the given [initializer].
*/
internal fun <T> mutableLazy(initializer: () -> T): MutableLazy<T> = MutableLazy(initializer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment