Skip to content

Instantly share code, notes, and snippets.

Created January 20, 2022 09:11
What would you like to do?
import java.lang.ref.WeakReference
import kotlin.reflect.KProperty
inline fun <reified T> weak() = WeakReferenceDelegate<T>()
inline fun <reified T> weak(value: T) = WeakReferenceDelegate(value)
* e.g. var x by weak<Context?>(activity)
class WeakReferenceDelegate<T> {
private var weakReference: WeakReference<T>? = null
constructor(value: T) {
weakReference = WeakReference(value)
operator fun getValue(thisRef: Any, property: KProperty<*>): T? = weakReference?.get()
operator fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
weakReference = WeakReference(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment