Skip to content

Instantly share code, notes, and snippets.

@sczerwinski
Created September 14, 2017 09:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sczerwinski/c84ba99d8326b4fefd1aa6cc7fa58992 to your computer and use it in GitHub Desktop.
Save sczerwinski/c84ba99d8326b4fefd1aa6cc7fa58992 to your computer and use it in GitHub Desktop.
Weak reference property delegate in Kotlin
class WeakReferenceProperty<T>(private val creator: () -> T) {
private var value: WeakReference<T> =
WeakReference(creator())
operator fun getValue(thisRef: Any?, property: KProperty<*>): T =
value.get() ?: creator().also { value = WeakReference(it) }
}
private fun <T> weak(creator: () -> T) =
WeakReferenceProperty(creator)
@kiruto
Copy link

kiruto commented Mar 29, 2018

Doing this you will have a strong reference with Type "() -> T".
When the Context-like variable in this closure, this closure will also have a strong reference with it's context.
For examble:

var a by weak { otherActivity.textview }

In this case above, the weak reference variable will have a strong reference with otherActivity.textview.

@kiruto
Copy link

kiruto commented Mar 29, 2018

You may write simple like this:

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?) {
        this.value = WeakReference(value)
    }
}

fun <T> weak(value: T) = WeakRefHolder(WeakReference(value))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment