commonMain.collections.CachedProperty.kt Maven / Gradle / Ivy
package org.openrndr.collections
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
class CachedProperty(val loader: () -> T) : ReadOnlyProperty {
private var value: CachedValue = CachedValue.Invalid
override fun getValue(thisRef: Any, property: KProperty<*>): T {
return when (val result = value) {
CachedValue.Invalid -> {
val newValue = loader()
value = CachedValue.Value(newValue)
newValue
}
is CachedValue.Value -> result.value
}
}
fun invalidate() {
value = CachedValue.Invalid
}
@Suppress("unused")
private sealed class CachedValue {
object Invalid : CachedValue()
class Value(val value: T) : CachedValue()
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy