Type of "this" inside coroutine

Viewed 165

I have function:

fun buttonClick(view: View){
    CoroutineScope(Dispatchers.Default).launch{ //this:CoroutineScope 
    Log.i(TAG,"${this.javaClass.toString()}")
    while (this.isActive) {
    //...
                }
         }
    }

In Logcat I see: class kotlinx.coroutines.StandaloneCoroutine. But if I step inside while (this.isActive) while debugging, I see call of CoroutineScope.isActive - not a call of StandaloneCoroutine (or AbstractCoroutine) method. i.e. "this" have CoroutineScope type- not StandaloneCoroutine. Could anyone explain this behavior of "this"?

2 Answers

When you inspect your code in the IDE, this is only known to be a CoroutineScope in the context of the code around it. The compiler only knows this to be a CoroutineScope, because that is the type defined in launch(). The actual instance of CoroutineScope in this case happens to be a StandaloneCoroutine instance which implements the interface of CoroutineScope. StandaloneCoroutine is a private implementation detail that you can only inspect at runtime using reflection (like you did by using javaclass).

StandaloneCoroutine is a subtype of all of these: Job, JobSupport, Continuation and CoroutineScope.

On the other hand, isActive is an extension property on CoroutineScope. Extension properties/functions do not belong to types, that is their fundamental characteristic. It doesn't matter which implementation of CoroutineScope you have, the implementation of the extension property is always the one and only public val CoroutineScope.isActive: Boolean, and the IDE took you there.

You may have been thrown off by the fact that this extension property is declared in the file CoroutineScope.kt, but if you check carefully, you'll see it's as top-level declaration and it's not inside the CoroutineScope interface (which is just a one-liner).

Related