WeakReference not working in Kotlin
<p>I'm implementing an <code>AsyncTask</code> in Kotlin, and I need a <code>WeakReference</code> for the callback that runs in the <code>onPostExecute()</code> method. I set the listener reference before calling <code>execute()</code>, but once <code>onPostExecute()</code> is called, the value of <code>WeakReference</code> is <code>null</code>.</p>

<pre><code>class PhotoRotationTask(uri: Uri, filePath: String, resolver: ContentResolver) : AsyncTask&lt;Int, Int, Int&gt;() {
    private var weakRef : WeakReference&lt;OnBitmapProcessedListener&gt;? = null

    var sourceUri : Uri
    var resolver : ContentResolver
    var destPath: String

    init {
        this.sourceUri = uri
        this.resolver = resolver
        this.destPath = filePath
    }

    fun setOnBitmapProcessedListener(listener: OnBitmapProcessedListener){
        weakRef = WeakReference(listener)
        Log.d("RotationTask", "set listener ${weakRef?.get() != null}") //This Log proves that weakRef is initialized before onPostExecute()
    }

    override fun doInBackground(vararg params: Int?): Int? {
        //Bitmap processing, weakRef is never called in this function
    }

    override fun onPostExecute(result: Int?) {
        Log.d("RotationTask", "result: $result") //This log proves that onPostExecute() is called eventually
        weakRef!!.get()?.onBitmapProcessed() //This implies that weakRef is not null, because app never crashes, but onBitmapProcessed is not called, so the reference is gone.
    }

}
</code></pre>

<p>The <code>listener</code> variable modifies my activity's UI, therefore it holds a reference to my activity. Activity is never recreated, my phone is still, never rotated or touched after AsyncTask starts. How is the <code>WeakReference</code> cleared??</p>