Skip to main content
InterviewHubPRO
Section Overview
Q38

Question 38 of 50

Part 3: K2 Compiler, KMP, Advanced Metaprogramming & Optimization (25 - 35)

76%
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?

  1. The Kotlin compiler rewrites suspend functions into Continuation-Passing Style (CPS), adding a hidden parameter: Continuation<T>.
  2. The compiler synthesizes an internal State Machine class:
    • Each suspension point (await(), delay()) becomes a case label inside a switch(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.