Lambda expression or anonymous function keep an implicit reference of the enclosing class


#1

When i pass a lambda expression or an anonymous function as a param, which will keep an implicit reference of the enclosing class. The situation may lead to memory leaks.

So, Kotlin may need something like WeakReference in java for function type can solve this problem.
like this:

fun foo(weak body: () -> Unit){
    // we check here if body  is still alive
    body?()
}

I am not sure it is the best implementation, but is cool if i we can use it in kotlin.


#2

Why not to use WeakReference class from java.lang.ref?

    fun foo(body: WeakReference<() -> Unit>){
        // we check here if body  is still alive
        body.get()?.invoke()
    }

#3

It is a good idea.
It will be not convenient when i try use kotlin in DSL.


#4

Maybe i can do like this:

fun foo(body: () -> Unit){
   val weakRefs = WeakReference(body)
    // we check here if body is still alive
    weakRefs.get()?.invoke()
}

but if it can be done by compiler will be fine.