orangy
class ResettableProperty<T>(val calculate: () -> T) {
private var lazyValue = lazy(calculate)
fun reset() {
lazyValue = lazy(calculate)
}
operator fun getValue(instance: Any, property: KProperty<*>): T = lazyValue.value
}
fun <T> Resettable.resettable(calculate: () -> T): ResettableProperty<T> {
return ResettableProperty(calculate).apply { register(this) }
}
open class Resettable {
private val properties = mutableListOf<ResettableProperty<*>>()
fun register(property: ResettableProperty<*>) {
properties.add(property)
}
fun reset() {
properties.forEach { it.reset() }
}
}
Using it:
class X : Resettable() {
var param = 1; set(value) {
field = value
reset()
}
val prop by resettable {
println("calculating prop with $param")
"[$param]"
}
}
fun main(args: Array<String>) {
val x = X()
println(x.prop)
println(x.prop)
x.param = 2
println(x.prop)
}
Prints
calculating prop with 1
[1]
[1]
calculating prop with 2
[2]