Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does the reference to "this" get resolved in nested scopes in Kotlin

enter image description here

In the above code snippet, how does Kotlin compiler know that collect in line #10 is to be invoked on the instance of the flow on which merge is invoked?

Isn’t this in line #10 referring to CoroutineScope as hinted in line #9 by the editor?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Code snippet for reference

fun <T> Flow<T>.merge(other: Flow<T>): Flow<T> = channelFlow {
    launch {
        collect { send(it) }
    }
    other.collect { send(it) }
}

>Solution :

Isn’t this in line #10 referring to CoroutineScope as hinted in line #9 by the compiler?

Yes, that’s true. But you do not use this, so there is no problem. Actually, there are three different this in your example. Type this and press Ctrl+Space to get this popup:

The first one is the obvious one from the enclosing launch, the second is the flow that your merge function is applied to and the third one is the receiver object of the channelFlow lambda.

Now to your initial question: How does collect know which this it should use? The answer is that it tries all out, beginning from the innermost this that is the CoroutineScope, then using the ProducerScope and finally the Flow. The first time it finds a function with a matching signature, that is the name and the parameter list must match, it stops and uses it. Otherwise it continues to find another receiver object for collect and displays an error if none could be found.

If you would have declared a matching collect function somewhere else in the type hierarchy of your merge function (if it is part of a class) or if one was defined at file level that collect function would even be preferred over all others.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading