Created
September 14, 2017 09:10
-
-
Save sczerwinski/c84ba99d8326b4fefd1aa6cc7fa58992 to your computer and use it in GitHub Desktop.
Weak reference property delegate in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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
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.