Here is small DSL I just hacked together and even ...
# getting-started
o
Here is small DSL I just hacked together and even didn’t run 🙂 in case you have mutliple such calculated properties, etc.
Copy code
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:
Copy code
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
Copy code
calculating prop with 1
[1]
[1]
calculating prop with 2
[2]
K 4