Jetpack Compose Mechanisms, Part 1: How the Compiler Turns a Function into a Composable

skydovesJaewoong Eum (skydoves)||22 min read

Jetpack Compose Mechanisms, Part 1: How the Compiler Turns a Function into a Composable

Jetpack Compose reached its stable 1.0 release in July 2021, and in May 2026 Google declared Android UI development Compose First. You probably write @Composable functions every day. Add that one annotation to an ordinary Kotlin function and it becomes UI that remembers values between runs, runs again on its own when data changes, and sometimes decides not to run at all. The body you wrote does none of this by itself, so what does?

In this article, you'll dive deep into what the Compose compiler does to that function, starting from a rule you have already hit and working inward: the calling context, the hidden $composer parameter, restart groups and idempotence, the compiler plugin model, and the generated code that decides whether a composable runs or skips.

This is the first article of a three part series based on my DroidKaigi 2026 & Droidcon Berlin 2026 talk, Jetpack Compose Mechanisms. You can follow along with the slides, and the diagrams in this series come from them. Part 2 follows the runtime and the UI layer, and Part 3 applies the whole picture to performance work.

The three layers: Compiler, runtime, and UI

Compose is usually introduced as a UI toolkit, but only two of its three parts are libraries. The third is a compiler plugin, and each part hands its output to the next.

Composable functions pass through the Compose compiler, the Compose runtime, and Compose UI before they become pixels

  1. The Compose compiler transforms your composable functions into a form the runtime can work with. It runs at build time.
  2. The Compose runtime executes the transformed functions and keeps a representation of the composition in memory: what was called, in what order, and which values were remembered along the way.
  3. Compose UI turns that representation into a tree of layout nodes, measures and places them, and draws the result into pixels.

You can see the split in a module's build file. The compiler is a Kotlin compiler plugin that is released with Kotlin and versioned with it, while the runtime and the UI layer are ordinary library dependencies. The runtime is spelled out below for clarity, though it usually arrives transitively through ui:

plugins {
    id("org.jetbrains.kotlin.plugin.compose")
}

dependencies {
    implementation(platform("androidx.compose:compose-bom:<version>"))
    implementation("androidx.compose.runtime:runtime")
    implementation("androidx.compose.ui:ui")
}

This article stays with the first stage and follows one small function through the compiler.

The fundamental problem: A function that returns nothing

Start with the smallest composable you can write:

@Composable
fun Greeting(name: String) {
    Text("Hello, $name")
}

Notice what the signature leaves out: a return type. Greeting returns Unit, like every composable that emits UI. It does not return a view or any other UI object. Instead, while it runs, it emits information into the composition, and the UI is built from what was emitted.

A composable takes data and, while it runs, emits into the composition

That leaves questions an ordinary Kotlin function has no answer for. If nothing is returned, where does the emitted information go, and how does Text know where it sits relative to Greeting? When the data behind name changes, how does Compose run again only the code that depends on it, instead of the whole screen? And when name has not changed, how does it know it can skip the work? A normal signature has no room to carry any of this, and a normal body has no way to report it. The compiler adds both: a parameter that carries the missing context, and calls in the body that report to the runtime.

The calling context: Composables can only be called from composables

The first visible effect of @Composable is a rule you have probably run into already. A composable function can only be called from another composable function:

@Composable
fun Place(name: String) {
    Person(name) // compiles
}

fun place(name: String) {
    Person(name) // compile error
}

@Composable
fun Person(name: String) {
    Text(name)
}

The second call fails with "@Composable invocations can only happen from the context of a @Composable function", and place itself gets a second error telling you that functions which invoke composables must be marked @Composable. This rule is known as the calling context, and if it feels familiar, that is because Kotlin coroutines have the same one.

The suspend analogy: Continuation passing style

A suspend function can only be called from another suspend function or from inside a coroutine:

suspend fun fetchProfile(name: String): Profile {
    return profileDao.findByName(name)
}

coroutineScope.launch {
    fetchProfile(name = "skydoves")
}

The reason is visible in what the Kotlin compiler produces. It rewrites every suspend function in continuation passing style: it appends a hidden $completion parameter of type Continuation, and it changes the return type to Any?, so the function can return either its result or a marker that says it has suspended:

fun fetchProfile(name: String, $completion: Continuation<Profile>): Any?

The continuation carries everything needed to resume the work later, and a function can only pass one along if it received one from its own caller. If you want to see the full transformation, The Machinery Behind the Magic: How Kotlin Turns suspend into State Machines walks through it. Composable functions follow the same pattern with a different hidden parameter.

The hidden parameter: $composer

Compile Greeting and its signature changes. The listings in this article are the compiler's output printed back as Kotlin, so they can contain things source code would not allow. The new signature looks like this:

fun Greeting(name: String, $composer: Composer?, $changed: Int)

Two parameters appeared that you never wrote. $composer is the runtime context, the object through which generated code talks to the Compose runtime. $changed carries what the caller already knows about each argument, and it comes back at the end of this article. You never pass either one yourself.

The compiler adds $composer to every composable, and every composable call inside a body passes the same instance along. Take a function that calls three other composables:

@Composable
fun NamePlate(name: String, lastname: String) {
    Column(modifier = Modifier.padding(16.dp)) {
        Text(text = name)
        Text(text = lastname)
    }
}

Leaving out the bookkeeping and the lambda's ColumnScope receiver, the output has this shape:

fun NamePlate(name: String, lastname: String, $composer: Composer?, $changed: Int) {
    Column(
        modifier = Modifier.padding(16.dp),
        content = { $composer, $changed ->
            Text(text = name, $composer)
            Text(text = lastname, $composer)
        },
        $composer,
    )
}

Column receives the composer as an extra argument, and the content lambda gains parameters of its own. When Column invokes the lambda, it hands the composer over, and the lambda passes it on to each Text. That is how the composer reaches code inside lambdas. Within one composition, the same composer reaches every call in the tree: at the root, setContent sets up the composition, the composition supplies the first composer, and from there it flows down through each composable call. Lazy list items, SubcomposeLayout, dialogs, and popups run in compositions of their own, each with its own composer.

The same composer instance is handed from setContent down through every composable call

This is the reason for the calling context rule. A suspend function needs a continuation from its caller, and a composable needs a $composer from its caller. Only a composable has one to pass down, so fun place() cannot call Person. Like suspend, the annotation splits functions into two kinds: a composable can call a regular function, but a regular function cannot call a composable. This is often called function coloring, and it is why the requirement spreads up through every caller.

If you examine the Composer interface, you'll find the protocol these generated calls speak. Its documentation is direct about who the caller is: "Composer is the interface that is targeted by the Compose Kotlin compiler plugin and used by code generation helpers." Trimmed to the members this article uses:

public sealed interface Composer {
    @ComposeCompilerApi public val skipping: Boolean
    @ComposeCompilerApi public fun startRestartGroup(key: Int): Composer
    @ComposeCompilerApi public fun endRestartGroup(): ScopeUpdateScope?
    @ComposeCompilerApi public fun skipToGroupEnd()
    @ComposeCompilerApi public fun changed(value: Any?): Boolean
    @ComposeCompilerApi public fun changedInstance(value: Any?): Boolean = changed(value)
    @InternalComposeApi public fun shouldExecute(parametersChanged: Boolean, flags: Int): Boolean
}

Each of these comes back below: startRestartGroup and endRestartGroup make a composable restartable, and the rest decide whether its body runs.

Recomposition: Functions that run more than once

A regular function runs when you call it, and that is the end of it. A composable can be executed again later, long after its caller has returned, whenever something it reads changes. That re-execution is called recomposition, and it is selective: when a state value changes, only the restartable scopes that read it run again, and the composables they call get a chance to skip.

When a State<Int> changes, only the composables that read it run again

For this to work, the runtime has to call one composable again on its own, without running the composable that called it. Threading $composer through every call was the compiler's first job; making composables restartable is the second. Not every composable gets this treatment: inline composables such as Column, Row, and Box, and composables that return a value, get no restart group of their own. The compiler wraps the body of Greeting like this, where <key> stands for an integer the compiler derives from where the function is declared and from its signature:

fun Greeting(name: String, $composer: Composer?, $changed: Int) {
    $composer = $composer.startRestartGroup(<key>)
    // the original body runs here, or is skipped
    $composer.endRestartGroup()?.updateScope { $composer, $force ->
        Greeting(name, $composer, updateChangedFlags($changed or 0b0001))
    }
}

Printed IR reassigns the $composer parameter, which source Kotlin would not allow. The two calls around the body work with groups. A group is a bracketed stretch of the composition: a start call opens it, an end call closes it, a key identifies it, and everything the code in between produces is recorded inside it. Part 2 looks at how groups are stored.

The runtime's default Composer implementation is GapComposer (named ComposerImpl in older releases). Looking at its startRestartGroup:

override fun startRestartGroup(key: Int): Composer {
    startReplaceGroup(key)
    addRecomposeScope()
    return this
}

It opens a group under the function's key, then attaches a RecomposeScope to it. The scope stands for this function at this position in the composition. It is created and stored during the first composition, and read back on every pass after that.

endRestartGroup closes the group and, in a normal run, returns that scope only when the body actually ran on this pass and read something that could invalidate it, such as a State created with mutableStateOf. Otherwise it returns null, which is why the generated code calls ?.updateScope. The lambda passed to updateScope is stored on the scope, and all it does is call the function again with the arguments from its last run, using the composition's composer positioned at this group. When the runtime decides that a scope must recompose, that lambda is the entry point it uses. Greeting itself reads no state, so in practice it gets no lambda and runs again only when its caller does; a composable that reads a State gets one.

Two details in the lambda are worth decoding. $changed or 0b0001 sets the lowest bit, the force bit, so a restart through the scope always runs the body instead of skipping it, which is also why the $force parameter goes unused. updateChangedFlags then turns every argument the caller had marked as changed into unchanged, because a restart replays exactly the arguments of the previous run; arguments whose state was unknown stay unknown and are compared again. This is also why the place where you read a state matters: the restart happens at the nearest restartable scope that did the read, so a read inside a small restartable child restarts only that child, while a read inside the content of an inline layout such as Column restarts the composable around it. Part 2 shows how that read is recorded.

Idempotence: Why running again and skipping are safe

Restarting one function in isolation is only safe if the function behaves predictably. Compose assumes composable functions are idempotent: running one again with the same inputs produces the same composition.

Running a composable twice with the same data emits the same composition

The runtime relies on this assumption whenever it runs a composable again, throws away a recomposition that was cancelled partway through, or skips a composable whose inputs have not changed. Skipping is safe only because running the function again would produce exactly what is already there. This is also why work with side effects belongs in effect handlers like LaunchedEffect and SideEffect rather than directly in the body. The body can run many times or not at all, and your code should not care which.

A compiler plugin: Why Compose is not an annotation processor

So far, one annotation has changed a function's signature and wrapped its body. Many Android libraries also act on annotations at build time: ButterKnife, Hilt and Dagger, Moshi, Room. It is natural to assume Compose works the same way, but it does not.

KSP and KAPT generate new source files next to yours, while a Kotlin compiler plugin works inside the compiler on FIR and IR

The key difference is what each tool is able to change. KAPT and KSP read your declarations and generate new source files, which are then compiled alongside the code you wrote. A generated Hilt component or a Room DAO implementation is new code, and neither processor can modify the functions you wrote. That is enough for view binding, dependency injection, JSON adapters, and persistence, because they only need to add code. When one of these libraries does need to alter existing code, as Hilt does when its Gradle plugin swaps in a generated superclass, it uses a separate bytecode transform outside the processor.

Compose needs to change code that already exists. It has to add parameters to your signatures, wrap your bodies in groups, and insert comparisons before the body runs. An annotation processor cannot edit a function body, so Compose is built as a Kotlin compiler plugin, which runs inside the compiler and can rewrite code as it compiles.

The K2 compiler works in two halves. The frontend parses your .kt files into FIR, a tree that holds your code in memory, and resolves it, working out what every name and call refers to. Resolution runs as a fixed series of phases, 13 of them, from IMPORTS to BODY_RESOLVE. The resolved FIR is then converted into IR, a second tree built for code generation, and the backend lowers that IR and turns it into .class files.

The K2 pipeline: the frontend parses source into FIR and resolves it, then the backend turns IR into class files

The Compose plugin hooks into both halves, with a different job in each. The KSP comparison diagram draws the plugin rewriting both trees; more precisely, Compose only checks FIR and rewrites IR.

The frontend: Analysis with FIR checkers

In the frontend, the plugin analyzes. FIR checkers run over resolved code and report Compose specific errors, which is where the calling context error comes from. ComposableFunctionCallChecker runs on every function call. Trimmed to the part that matters here:

object ComposableFunctionCallChecker : FirFunctionCallChecker(MppCheckerKind.Common) {
    context(context: CheckerContext, reporter: DiagnosticReporter)
    override fun check(expression: FirFunctionCall) {
        val calleeFunction = expression.calleeReference.toResolvedFunctionSymbol()
            ?: return
        if (calleeFunction.isComposable(context.session)) {
            checkComposableCall(expression, calleeFunction, context, reporter)
        }
    }
}

When the callee is composable, checkComposableCall walks outward through the enclosing scopes looking for a composable context: a composable function, a composable lambda, or an inline lambda inside one of them. If it finds one, the call is valid. If the walk ends without one, it reports COMPOSABLE_INVOCATION on the call. On the way, it also reports COMPOSABLE_EXPECTED on place, the regular function where the walk stopped, which is the second error you saw. The frontend also registers composable function types as a kind of function type of their own, one that an ordinary function type cannot be converted into. That registration is what makes function coloring a property of the type system rather than a convention.

The backend: Transformation with IR lowerings

In the backend, the plugin transforms. It registers a series of IR lowerings, passes that each rewrite the tree one step closer to bytecode, and runs them in a fixed order. Two of them produce what this article reads: ComposerParamTransformer adds $composer and $changed to every composable (plus $default when it has default arguments), and ComposableFunctionBodyTransformer wraps every body in groups and skip checks. The others, such as stability inference and lambda memoization, are covered in How the Compose Compiler Rewrites Your @Composable.

Because the checkers run on FIR before any lowering, their errors point at the code you wrote. Because the lowerings run only after analysis succeeds, they are free to rewrite that code completely.

Reading the generated code: How a composable decides to skip

Back to Greeting. You have seen the calling convention and the restart group; the code between them is what decides whether the body runs. It does two things. It works out whether name changed, trusting the caller when the caller already knows and comparing against the value stored on the previous run when it does not. Then it either runs the body, or jumps past it and keeps what the last run produced. The bookkeeping is done with bitmasks, so start with what the bits mean.

The $changed bits: What the caller already knows

$changed packs a small state for every parameter into an Int, ten parameters per Int with receivers included, so a function with more parameters receives more than one $changed. Bit 0 is the force bit you saw in the restart lambda. After it, each parameter gets a slot of three bits: the low two bits describe what the caller knows about that argument, and the third carries stability information, which comes back near the end of this article. The compiler defines the states in ParamState:

enum class ParamState(val bits: Int) {
    Uncertain(0b000),
    Same(0b001),
    Different(0b010),
    Static(0b011),
    // ...
}
  • Uncertain: the caller does not know whether the value changed, so the callee has to compare it.
  • Same: the caller already knows the value is the same as in the previous execution.
  • Different: the caller already knows the value changed.
  • Static: the value is known to never change while the program runs, like a constant.

Because the slot for name, the first parameter, starts at bit 1, each state is shifted left by one: Same (0b001) becomes 0b0010, Different (0b010) becomes 0b0100, and the mask 0b0110 covers exactly the slot's two state bits. This also explains updateChangedFlags in the restart lambda: it turns every Different into Same.

With that, the full output for Greeting reads naturally. The optional source information and tracing calls are removed, and the call to Text is shortened: the real call also passes each of Text's default parameters and the extra bitmasks that go with them.

fun Greeting(name: String, $composer: Composer?, $changed: Int) {
    $composer = $composer.startRestartGroup(<key>)
    var $dirty = $changed
    if ($changed and 0b0110 == 0) {
        $dirty = $dirty or if ($composer.changed(name)) 0b0100 else 0b0010
    }
    if ($composer.shouldExecute($dirty and 0b0011 != 0b0010, $dirty and 0b0001)) {
        Text("Hello, $name", $composer, 0)
    } else {
        $composer.skipToGroupEnd()
    }
    $composer.endRestartGroup()?.updateScope { $composer, $force ->
        Greeting(name, $composer, updateChangedFlags($changed or 0b0001))
    }
}

The skip decision: Step by step

Read the body from the top:

  1. Working copy: $dirty starts as a copy of $changed. It is the function's view of what is known about its parameters.
  2. Uncertain check: $changed and 0b0110 == 0 asks whether name is Uncertain. Only then does Greeting compare the value itself. If the caller already knew, the comparison is skipped.
  3. Comparison: $composer.changed(name) compares the value against the one from the previous composition and writes Different (0b0100) or Same (0b0010) into $dirty.
  4. Decision: shouldExecute receives two arguments. The mask 0b0011 reads two bits at once: the force bit, and the low bit of name's slot, which is set for both Same and Static. The result equals 0b0010 only when that low bit is set and the force bit is clear, so the first argument is false only when name is known to be unchanged and nothing forces a run. The second argument passes the force bit along. When shouldExecute returns true, the original body runs.
  5. Skip: otherwise, skipToGroupEnd() moves the runtime past the group and keeps what Greeting produced last time, without executing a line of its body. If a scope nested inside the group was invalidated, such as one inside Text, the runtime recomposes that scope on the way through, which is how a parent can skip while one of its children still updates.

The comparison itself is short. Looking at changed in GapComposer:

override fun changed(value: Any?): Boolean {
    return if (nextSlot() != value) {
        updateValue(value)
        true
    } else {
        false
    }
}

nextSlot() reads the value stored at this position during the previous composition, and != compares the two with equals(). When they differ, the new value is written back so the next pass has something to compare against. The argument lives in the composition itself, at a position the runtime walks in the same order every time, which is the subject of Part 2.

A type is stable when Compose can trust its equals() and is notified whenever its public state changes. For a parameter whose type is known to be unstable, strong skipping mode, which current compilers enable by default, makes the generated code call changedInstance instead. It is the same method with !== in place of !=. Function types such as lambdas are compared with changedInstance in every mode, and when stability can only be decided at runtime, the stability bit in $changed picks between the two. Part 3 shows what that difference costs.

One more detail is easy to miss. Text receives 0 as its own $changed, because "Hello, $name" is a new string built in the body and nothing is known about it. Had Greeting called Text(name) directly, the compiler would pass 0b1110 and $dirty, the bits of name's slot, instead of 0. Forwarding what is already known this way means a value is compared once near the top of the tree rather than again at every level.

shouldExecute: The skip check in the runtime

In GapComposer, shouldExecute first handles pausable composition, which lets the runtime pause new content partway through composing it and resume later. That only applies while new content is being inserted or reused. In every other case, the method ends with a single line:

return parametersChanged || !skipping

The body runs if a parameter changed, or if the composer is not in a position to skip. Inserting and reusing were already answered by the pausing branch above, so on this line skipping mostly answers one question: does this scope have a pending invalidation, even though it was reached because its caller ran again? A changed CompositionLocal provider or a forced recomposition also turns it off. In those situations the body runs even if every parameter is the same. When the runtime restarts a scope on its own, through the stored lambda, it clears the invalidation first, so it is the force bit, not skipping, that makes the body run.

Compilers before Kotlin 2.2 emitted the same check inline, as $dirty and 0b0011 != 0b0010 || !$composer.skipping, which is the form you will see on the talk's slides. Kotlin 2.2 turned the compiler's PausableComposition flag on by default, and the compiler now calls shouldExecute so the runtime can make the pausing decision. It still emits the inline form when that flag is turned off, or when the Compose runtime on the classpath predates shouldExecute.

Conclusion

In practice, the generated code is where questions about recomposition get their answers. When a composable recomposes more often than you expect, or refuses to skip, check what the compiler decided about it instead of guessing. The Compose compiler reports list, for every composable, whether it is restartable and skippable and how each parameter's stability was inferred, and Part 3 shows how to read them. You will rarely read the bitmasks by hand, but the rule they encode is worth keeping: a composable skips only when each argument its body uses matches the one stored on its previous run, by equals() for stable types and by identity for unstable types and lambdas, so the arguments you pass decide how often that can happen.

@Composable is not a tag that something looks up at runtime. It is a calling convention, like suspend, and the compiler fulfills it by rewriting your function so that every call reports to the runtime. That rewrite is only half of the conversation, though. Part 2 follows what it records into the runtime's SlotTable and on to the UI that turns it into pixels.

If you want to go deeper than this series can, my book Jetpack Compose Mechanisms walks through the compiler, the runtime, and Compose UI in much more detail, reading each one from the actual source the same way this series does.

As always, happy coding!

— Jaewoong (skydoves)