If the goal is to have a lazy initialized var property , which can be reset to its initial state, you can adapt Kotlin SynchronizedLazyImpl to resolve the invalidate function:
private object UNINITIALIZED_VALUE class InvalidatableLazyImpl<T>(private val initializer: () -> T, lock: Any? = null) : Lazy<T>, Serializable { @Volatile private var _value: Any? = UNINITIALIZED_VALUE private val lock = lock ?: this fun invalidate(){ _value = UNINITIALIZED_VALUE } override val value: T get() { val _v1 = _value if (_v1 !== UNINITIALIZED_VALUE) { return _v1 as T } return synchronized(lock) { val _v2 = _value if (_v2 !== UNINITIALIZED_VALUE) { _v2 as T } else { val typedValue = initializer() _value = typedValue typedValue } } } override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet." operator fun setValue(any: Any, property: KProperty<*>, t: T) { _value = t } }
What could be used as follows:
private val fooDelegate = InvalidatableLazyImpl({"bar"}) var foo:String by fooDelegate println(foo); // -> "bar" foo = "updated" println(foo); // -> "updated" fooDelegate.invalidate() println(foo); // -> "bar"
Obviously, it would be possible to change the implementation of the delegate so that the null value acted as reset, however this could make the code more difficult to reason about ie:
println(obj.foo);
source share