any Delegate similar to `lazy` in functionality bu...
# announcements
j
any Delegate similar to
lazy
in functionality but resettable?
t
ReadWriteProperty
?
s
you can always implement your own.
s
ReadWriteProperty is an interface. I don't think a common implementation exists that does what you want.
i
Copy code
fun <T> mutableLazy(initializer: () -> T): MutableLazy<T> = MutableLazy(initializer)

class MutableLazy<T>(val init: () -> T) : ReadWriteProperty<Any?, T> {

    private var value: T? = null

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return when (val v = value) {
            null -> {
                val initResult = init()
                value = initResult
                initResult
            }
            else -> v
        }
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        this.value = value
    }
}

//usage
var someLazyNumber: Int by mutableLazy { 10 }
someLazyNumber = 15
something like that?
m
yeah this one is not thread-safe though
i found with mutable lazy vars consumers soon get more ambitious, may require replacing the supplier, checking if the instance had been set in the first place, following some handy lambdas in that respect, so
ReadWriteProperty
is probably not a good fit except for most basic implementations.
or delegates in the first place
l
Here's a non mutable but resettable lazy delegate. Can be made multithread-safe by taking inspiration from stdlib implementation: https://github.com/LouisCAD/Splitties/blob/develop/modules/preferences/src/commonMain/kotlin/splitties/preferences/ResettableLazy.kt