Kotlin & Coroutines (50 Qs)•Part 3: K2 Compiler, KMP, Advanced Metaprogramming & Optimization (25 - 35)
Kotlin Coroutines Internals: Continuation-Passing Style (CPS) and State Machine compilation.
senior LevelPerformance
In Simple Words: How does a coroutine "pause" and "resume" without blocking OS threads?
- The Kotlin compiler rewrites
suspendfunctions into Continuation-Passing Style (CPS), adding a hidden parameter:Continuation<T>. - The compiler synthesizes an internal State Machine class:
- Each suspension point (
await(),delay()) becomes acaselabel inside aswitch(label)statement. - When a suspension point completes, the runtime invokes
continuation.resumeWith(result), re-entering the state machine at the exact next label without allocating new thread stacks.
- Each suspension point (