Sobes.tech
Middle — Middle+

What internal representation is used in the compiler to implement suspend functions in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, suspend functions are compiled into a state machine. The compiler transforms a suspend function into a class that implements the Continuation interface. Internally, a state object is used to store the current execution point and local variables, so that when the function resumes, it continues from the correct place.

This allows suspending the execution of a suspend function without blocking the thread, saving the context, and resuming later. This transformation is done through code rewriting into a chain of calls passing a Continuation object.

Here's a simplified example:

suspend fun example() {
    // ...
}

// The compiler generates a class that stores state and implements Continuation
class ExampleContinuation(val completion: Continuation<Unit>) : Continuation<Unit> {
    var label = 0
    override val context = completion.context

    override fun resumeWith(result: Result<Unit>) {
        when(label) {
            0 -> {
                label = 1
                // ...
            }
            1 -> {
                // continuation
            }
        }
    }
}