Coroutine vs. Job

“This ended up being longer than I expected, so take a deep breath and dive in with an open, knowledge-thirsty mind…”

Appreciate your effort ! (Spoiler. I’m still not nconvinced : -)

Okay there we go, I think I found the cause of confusion here. I haven’t supported the statement Continuation = Coroutine, which is purely my fault, so sorry for that.

No worries.

As you can see, this function returns a Continuation, which is the only representation in the Kotlin stdlib for a coroutine.

Says you.

The Kotlin docs says it’s an: “Interface representing a continuation after a suspension point that returns a value of type T.”

Continuation

I say It’s a callback to the code which comes after the Coroutine invocation

In any case, this Interface represents implementation details. It is of minimal concern (if any) to the user of the library.

For more evidence, all suspending lambdas are of this following class …

The Kotlin compiler also makes references to suspend functions being represented as Continuations. For example, one of the transformations performed is described like this in the source code…

and its implementation creates a class extending SuspendLambda (which, if you remember, extends Continuation) and adds an invoke method to it that calls invokeSuspend. It also directly states in a comment…

Of course it makes sense that SuspendLambda is a Continuation but these are there to implement the coroutine concept they do not represent the concept

Simply, all coroutines are represented as Continuation,

Almost. A coroutine (the higher level concept) is implemented via a chain of Continuations.

and so I’m led to strongly believe that the term “Coroutine” absolutely represents execution mechanics

In general, I would avoid defining concepts based on implementation details which are subject to change.

I suggest you check out the Wiki for coroutines at Coroutine - Wikipedia it’s a good read, it does not focus on any specific execution mechanics.

Notice the following in particular:

“an instance of a subroutine only returns once, and does not hold state between invocations. By contrast, coroutines can exit by calling other coroutines, which may later return to the point where they were invoked in the original coroutine; from the coroutine’s point of view, it is not exiting but calling another coroutine”

And see how clearly it appears in Kotlin

val coroutine = launch {
    // This block is the BODY of the coroutine, 
    // Kotlin (very appropriately) calls it the "Coroutine Scope" - it's the execution scope of the coroutine
    delay(200) // exit
    println("Continuing") // return
  }

All I’m saying is that having a type Job seems totally unnecessary to model a Coroutine.

The return type of launch should be named “Coroutine” not “Job” and all is good!