https://kotlinlang.org logo
Title
j

jishindev

07/23/2019, 12:22 PM
any Delegate similar to
lazy
in functionality but resettable?
t

thana

07/23/2019, 12:25 PM
ReadWriteProperty
?
s

Stephan Schroeder

07/23/2019, 12:27 PM
you can always implement your own.
s

streetsofboston

07/23/2019, 12:27 PM
ReadWriteProperty is an interface. I don't think a common implementation exists that does what you want.
i

Icaro Temponi

07/23/2019, 4:32 PM
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

masc3d

07/23/2019, 4:58 PM
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

louiscad

07/27/2019, 8:46 AM
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