```fun main() = runBlocking { // this: CoroutineSc...
# coroutines
j
Copy code
fun main() = runBlocking { // this: CoroutineScope

    coroutineScope { // Creates a coroutine scope
        println(this)
        println(this@runBlocking)
...
and the printed result is:
Copy code
"coroutine#1":ScopeCoroutine{Active}@64a294a6
"coroutine#1":BlockingCoroutine{Active}@7e0b37bc
Why do they have the same name “coroutine#1”? If they are different coroutines, shouldn’t they have different labels? Am I missing something?
f
I think
coroutine#1
is the parent of both, in this case, thew
runBlocking
Try this, and you will see the difference:
Copy code
import kotlinx.coroutines.*

fun main() = runBlocking { // this: CoroutineScope
    coroutineScope { // Creates a coroutine scope
        println(this)
        println(this@runBlocking)
        test()
    }
}

fun test() = runBlocking {
    println(this)
}
e
coroutineScope { ... }
does not create a new coroutine, even though it has its own
Job
instance, and thus also uses the same id.
🙂 3
j
I see, I just vaguely thought after simply skimming through the
coroutineScope
function
Copy code
public suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R =
    suspendCoroutineUninterceptedOrReturn { uCont ->
        val coroutine = ScopeCoroutine(uCont.context, uCont)
        coroutine.startUndispatchedOrReturn(coroutine, block)
    }
that it would create a new coroutine. Then I guess here
val coroutine = ScopeCoroutine(uCont.context, uCont)
does not return a new coroutine.
e
The trick is how you define a "coroutine". Here we use a narrower definition, where a "coroutines" is something that works concurrently with the rest of your code. Since
coroutineScope { ... }
(unline
launch
) is not concurrent with the surrounding code we don't call it a "coroutine builder" and we don't consider it to actually create a new coroutine.
👍 1