1717
1818package com.lambda.util.collections
1919
20+ /* *
21+ * A lazy-initialized value holder that allows the stored value to be reset and re-initialized on demand.
22+ *
23+ * This class supports lazy initialization for a value of type [T] using a provided initializer function.
24+ * Once the value is accessed, it is initialized and stored. The `update` function can be called to reset
25+ * the value, allowing it to be re-initialized using the same initializer function.
26+ *
27+ * @param T The type of the value being lazily initialized and managed.
28+ * @constructor Accepts an initializer function that defines how the value should be created.
29+ */
2030class UpdatableLazy <T >(private val initializer : () -> T ) {
2131 private var _value : T ? = null
2232
33+ /* *
34+ * Lazily initializes and retrieves a value of type [T] using the provided initializer function.
35+ * If the value has not been initialized previously, the initializer function is called
36+ * to generate the value, which is then cached for subsequent accesses.
37+ *
38+ * This property ensures that the value is only initialized when it is first accessed,
39+ * and maintains its state until explicitly updated or reset.
40+ *
41+ * @return The lazily initialized value, or `null` if the initializer function
42+ * is designed to produce a `null` result or has not been called yet.
43+ */
2344 val value: T ?
2445 get() {
2546 if (_value == null ) _value = initializer()
2647 return _value
2748 }
2849
50+ /* *
51+ * Resets the current value to a new value generated by the initializer function.
52+ *
53+ * This function effectively re-initializes the stored value by discarding the existing value,
54+ * if any, and calling the initializer function to compute a new value.
55+ * It is useful for scenarios where the lazily computed value needs to be refreshed or updated
56+ * explicitly.
57+ */
2958 fun update () {
3059 _value = initializer()
3160 }
3261}
3362
63+ /* *
64+ * Provides a lazily-initialized value that can be reset and re-initialized on demand.
65+ * This function utilizes an `UpdatableLazy` to manage the lazy initialization and allow updates.
66+ *
67+ * @param T The type of the value to be lazily initialized.
68+ * @param initializer A lambda function that defines how the value should be computed.
69+ * @return An `UpdatableLazy` instance capable of managing a lazily-initialized value.
70+ */
3471fun <T > resettableLazy (initializer : () -> T ) = UpdatableLazy (initializer)
0 commit comments