All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.collections.CachedProperty.kt Maven / Gradle / Ivy

There is a newer version: 0.4.5-alpha6
Show newest version
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