Lazy variable with reset

I want to create a variable of a certain type that is not null, say, for example, Foo.

Then I want all access to the variable to be returned by Foo, like the lazy delegate, however I also want to be able to reset it.

Sort of:

var foo : String by Foo(init: {"bar"}) print(foo) // prints "bar" foo = null // or foo.reset() print(foo) // prints "bar" 

The problem I'm trying to solve: I have an index for the adapter that I need to recreate when the adapter contents change. Therefore, when I change, I want to clear the index, and the next time someone tries to access it, I want to recreate it.

+6
source share
1 answer

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); //-> prints "bar obj.foo = null //reset the value, implicitely println(obj.foo); //-> prints "bar", but hey didn't I just said `null` 
+6
source

All Articles