WeakReference + Lazy?

Hey Kotlin community!

Lately, I am using the lazy delegate a lot to avoid unnecessary object creation, but as far I know, the value of a Lazy object will never be garbage collected when memory is (almost) full. Would it be possible to have a weak lazy delegate which would not prevents its value from beeing garbage collected?

1 Like

Yes, you can write such a delegate by yourself.

How do you think about adding it to the standard library?

1 Like

Today I was longing for iOS weak properties and wrote the following, which you might want to update for laziness.

/**
 * Experimental delegate to have weak properties without boilerplate.
 *
 * See [weakRef] for usage.
 */
class WeakRefHolder<T>(private var _value: WeakReference<T?>) {

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
        return _value.get()
    }

    operator fun setValue(
        thisRef: Any?, property: KProperty<*>, value: T?
    ) {
        _value = WeakReference(value)
    }
}

/**
 * Use the `by` keyword to delegate weak references.
 *
 * Internally this creates a [WeakRefHolder] that will store the real
 * [WeakReference]. Example usage:
 *
 *     var weakContext: Context? by weakRef(null)
 *     …
 *     weakContext = strongContext
 *     …
 *     context = weakContext
 */
@Suppress("NOTHING_TO_INLINE")
inline fun <T> weakRef(value: T) = WeakRefHolder<T>(WeakReference(value))

Is it possible to write such a delegate without depending on kotlin.reflect? That library adds over 1MB to an apk. Somehow I can use lazy delegate without kotlin.reflect being added to APK.

If I am not mistaking, the above example does not require kotlin.reflect. KProperty is just embedded in the stdlib, kotlin.reflect is needed for more advanced introspection. There is no reason you should add a dependency to write delegates.