The Ultimate Breakdown of Kotlin Coroutines. Part 2. Continuation Passing Style and Resumption.
This is a continuation of series about coroutines internals. In the first part I explained how the compiler turns sequential code into suspendable by turing it into state-machines and how suspension works. This part covers continuation passing style - the reason for two-world model, and the counterpart of suspension - resumption. Continuation Passing Style In the first blogpost I touched upon the COROUTINE_SUSPENDED marker and said that suspending functions and lambdas return the marker when they suspend. Consequently, every suspend function return returnType | COROUTINE_SUSPENDED union type. However, since neither Kotlin nor JVM support union types, every coroutine's return type is Any? (also known as java.lang.Object ) at runtime. Let's now look to resume process closely. Suppose we have a couple of coroutines, one of them calls the other: fun main () { val a: suspend () -> Unit = { suspendMe() } val b: suspend () -> Unit = { a() } builder { b()...