WeakReference + Lazy?


#1

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?


#2

Yes, you can write such a delegate by yourself.


#3

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


#4

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))