Skip to content
Muhammed Ali
Kocabey

Generating Android Navigation Graphs with KSP

With type-safe Navigation Compose, adding a screen still takes three edits: define the route, write the composable<T> block, and add that block to the right NavHost. The compiler doesn't check that the last two happened. In this post we'll generate that wiring at compile time with Kotlin Symbol Processing (KSP): each screen carries a @Destination annotation, a SymbolProcessor collects them, and KotlinPoet writes one NavGraphBuilder extension per module.

The processor is small, but it is complete. Along the way we'll look at the parts that decide whether it actually works: validation and deferred symbols, the aggregating flag, and the fact that KSP only sees one module at a time.

Why generate the graph

Since Navigation 2.8.0 you can define routes as @Serializable types, register them with composable<T> and read arguments back with backStackEntry.toRoute<T>(). That got rid of string routes like "profile/{userId}" and the typos in argument keys that came with them.

Registering screens is still manual, though. In a small app that's fine. With dozens of destinations spread across feature modules, the NavHost becomes a long list you maintain by hand, and a screen you forgot to register only shows up at runtime. If the graph is generated from the screens themselves, there is nothing to forget. It's the same reason I moved repetitive back handling into extension functions over OnBackPressedDispatcher: mechanical wiring is better off out of hand-written code.

KSP in short, and why not KAPT

KSP is a Kotlin-first API that lets you read source code as resolved symbols and generate new source files during compilation. KAPT works differently: it generates Java stubs for your Kotlin code, which means resolving every type up front, and then hands them to javac. KSP has no stubs and resolves a type only when the processor asks for it; the Kotlin docs say this makes annotation processing up to about twice as fast. KSP also understands Kotlin constructs that have no Java equivalent, such as extension functions and declaration-site variance.

KSP is also read-only. A processor can't change existing code; it can only add new files. So we won't touch the screens. We read them and generate a separate file that wires them together. That's a different approach from Aspectify, my AOP library, which works at runtime through a java.lang.reflect.Proxy. Here everything happens at compile time, and the result is plain Kotlin you can open and read.

Project setup

We need three pieces: an annotation module (plain Kotlin/JVM), a processor module (also JVM), and the feature modules that use them.

// navgraph-processor/build.gradle.kts
dependencies {
    implementation("com.google.devtools.ksp:symbol-processing-api:<ksp-version>")
    implementation("com.squareup:kotlinpoet:<kotlinpoet-version>")
    implementation("com.squareup:kotlinpoet-ksp:<kotlinpoet-version>")
}
// feature/profile/build.gradle.kts
plugins {
    id("com.google.devtools.ksp")
}

dependencies {
    implementation(project(":navgraph-annotations"))
    ksp(project(":navgraph-processor"))
}

ksp {
    arg("navgraph.package", "com.example.feature.profile")
    arg("navgraph.name", "profile")
}

The feature module also needs the usual Navigation Compose and kotlinx.serialization setup. The two arg values reach the processor as options; we'll see below why each module needs its own.

The annotation

Keep the annotation small. It marks a composable as a destination and points to the @Serializable route type that identifies it.

package com.example.navgraph

import kotlin.reflect.KClass

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.SOURCE)
annotation class Destination(val route: KClass<*>)

SOURCE retention is enough because KSP reads the annotation from source. It only has to exist during compilation and leaves nothing in the bytecode.

The screens use ordinary type-safe routes:

package com.example.feature.profile

import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import com.example.navgraph.Destination
import kotlinx.serialization.Serializable

@Serializable
data class ProfileRoute(val userId: String)

@Serializable
data object EditProfileRoute

@Destination(route = ProfileRoute::class)
@Composable
fun ProfileScreen(route: ProfileRoute, navController: NavController) {
    // ...
}

@Destination(route = EditProfileRoute::class)
@Composable
fun EditProfileScreen(navController: NavController) {
    // ...
}

The convention is simple: a screen can take its own route type and a NavController, and nothing else. The generator can't know which lambdas you'd want to pass, so it needs a fixed contract like this. Passing NavController into screens has a cost: the Android docs recommend exposing navigation as lambdas so screens stay easy to test and preview. If that matters to you, take a small Navigator interface of your own instead of NavController. The processor logic stays the same.

Writing the SymbolProcessor

A KSP processor has two parts: a provider that KSP discovers, and the processor itself.

The provider

class NavGraphProcessorProvider : SymbolProcessorProvider {
    override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor =
        NavGraphProcessor(
            codeGenerator = environment.codeGenerator,
            logger = environment.logger,
            options = environment.options,
        )
}

KSP finds the provider through a one-line service file, src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider, which contains the provider's fully qualified class name. AutoService can generate this file, but then the processor module needs another annotation processor of its own; for a single line, writing it by hand is simpler.

Finding and validating screens

class NavGraphProcessor(
    private val codeGenerator: CodeGenerator,
    private val logger: KSPLogger,
    private val options: Map<String, String>,
) : SymbolProcessor {

    private var generated = false

    override fun process(resolver: Resolver): List<KSAnnotated> {
        val screens = resolver
            .getSymbolsWithAnnotation(DESTINATION)
            .filterIsInstance<KSFunctionDeclaration>()
            .toList()
        if (screens.isEmpty()) return emptyList()

        // The graph is a single file. If any screen can't be resolved yet,
        // defer all of them and generate the file in a later round.
        if (screens.any { !it.validate() }) return screens

        if (generated) {
            logger.error("@Destination found after the graph was generated", screens.first())
            return emptyList()
        }
        generated = true

        val destinations = screens.mapNotNull { it.toDestination() }
        if (destinations.size == screens.size) {
            writeGraph(destinations)
        }
        return emptyList()
    }

    private companion object {
        const val DESTINATION = "com.example.navgraph.Destination"
        const val NAV_CONTROLLER = "androidx.navigation.NavController"
        val COMPOSABLE = MemberName("androidx.navigation.compose", "composable", isExtension = true)
        val TO_ROUTE = MemberName("androidx.navigation", "toRoute", isExtension = true)
    }
}

KSP can run a processor in several rounds. A screen may refer to a type that another processor hasn't generated yet; in that case validate() returns false. Whatever process() returns is deferred to the next round, and getSymbolsWithAnnotation hands those symbols back together with symbols from newly generated files.

Most examples partition the symbols, process the valid ones and return only the invalid ones. That's fine when each symbol produces its own file. Our output is a single file, though. If we wrote the graph with the valid screens in round one, we'd have to create the same file again in round two, and KSP doesn't allow creating the same file twice. We also can't keep the round-one symbols and add the rest later, because KSP symbol objects shouldn't be held across rounds. So if anything is unresolved, we defer every screen and write the file once, in the round where everything resolves. The generated flag catches the case where a later round brings in new screens after the file is written.

Reading the annotation into a model

The rest of the processor works with a small model built from KotlinPoet types:

private enum class ScreenParameter { Route, NavController }

private class DestinationModel(
    val screen: MemberName,
    val route: ClassName,
    val parameters: List<ScreenParameter>,
    val file: KSFile?,
)

Reading the annotation, inside NavGraphProcessor:

private fun KSFunctionDeclaration.toDestination(): DestinationModel? {
    val annotation = annotations.first {
        it.annotationType.resolve().declaration.qualifiedName?.asString() == DESTINATION
    }
    val routeType = annotation.arguments
        .first { it.name?.asString() == "route" }
        .value as KSType
    val routeName = routeType.declaration.qualifiedName?.asString()

    val screenParameters = parameters.map { parameter ->
        when (parameter.type.resolve().declaration.qualifiedName?.asString()) {
            routeName -> ScreenParameter.Route
            NAV_CONTROLLER -> ScreenParameter.NavController
            else -> {
                logger.error(
                    "Unsupported parameter '${parameter.name?.asString()}' in a @Destination screen",
                    parameter,
                )
                return null
            }
        }
    }

    return DestinationModel(
        screen = MemberName(packageName.asString(), simpleName.asString()),
        route = routeType.toClassName(),
        parameters = screenParameters,
        file = containingFile,
    )
}

When you read a KClass annotation argument, KSP gives you a KSType, not a reflected class. toClassName() comes from kotlinpoet-ksp and turns it into a KotlinPoet ClassName. For an unsupported parameter we call logger.error with the parameter as the node, so the build fails and the error points at the right line in the screen.

Generating the graph with KotlinPoet

You can write raw text through CodeGenerator.createNewFile(...), but once the output has imports and nested blocks, KotlinPoet is much easier. It manages imports, and kotlinpoet-ksp writes the FileSpec through KSP's CodeGenerator.

private fun writeGraph(destinations: List<DestinationModel>) {
    val packageName = options["navgraph.package"]
    val name = options["navgraph.name"]
    if (packageName == null || name == null) {
        logger.error("Set navgraph.package and navgraph.name with ksp { arg(...) }")
        return
    }

    val graphFunction = FunSpec.builder("${name}Destinations")
        .receiver(ClassName("androidx.navigation", "NavGraphBuilder"))
        .addParameter("navController", ClassName("androidx.navigation", "NavController"))

    destinations.sortedBy { it.screen.canonicalName }.forEach { destination ->
        val arguments = destination.parameters.map { parameter ->
            when (parameter) {
                ScreenParameter.Route -> CodeBlock.of("it.%M<%T>()", TO_ROUTE, destination.route)
                ScreenParameter.NavController -> CodeBlock.of("navController")
            }
        }
        graphFunction.addStatement(
            "%M<%T> { %M(%L) }",
            COMPOSABLE,
            destination.route,
            destination.screen,
            arguments.joinToCode(),
        )
    }

    FileSpec.builder(packageName, "${name.replaceFirstChar { it.uppercase() }}NavGraph")
        .indent("    ")
        .addFunction(graphFunction.build())
        .build()
        .writeTo(
            codeGenerator = codeGenerator,
            aggregating = true,
            originatingKSFiles = destinations.mapNotNull { it.file },
        )
}

Sorting the screens is deliberate. The order of getSymbolsWithAnnotation isn't something to rely on, and the same input should always produce the same file; otherwise the output can change between builds for no reason and the build cache stops helping.

The generated file for the profile module:

package com.example.feature.profile

import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute

public fun NavGraphBuilder.profileDestinations(navController: NavController) {
    composable<EditProfileRoute> { EditProfileScreen(navController) }
    composable<ProfileRoute> { ProfileScreen(it.toRoute<ProfileRoute>(), navController) }
}

writeTo(codeGenerator, aggregating, originatingKSFiles) is a thin wrapper over KSP's own API. Without KotlinPoet, the same thing looks like this:

val dependencies = Dependencies(aggregating = true, *files.toTypedArray())
codeGenerator.createNewFile(dependencies, packageName, fileName)
    .bufferedWriter()
    .use { writer -> fileSpec.writeTo(writer) }

Dependencies is where you tell KSP which source files the output came from and whether it is aggregating. The next section is about why that matters.

Trade-offs and pitfalls

Code generation isn't free, and most of the cost is in the contract with the build system.

The aggregating flag

KSP can process incrementally only if each output declares the source files it came from and whether it is isolating or aggregating. An isolating output depends only on the files it lists; a change elsewhere doesn't touch it. A one-class-per-annotated-class generator is the typical isolating case. An aggregating output, according to the KSP docs, may depend on any input, so any change in the module's sources, including new files, makes KSP re-run the processor for it.

The graph has to be aggregating. When you add a new screen file, it must end up in the existing graph file, and only aggregating outputs are invalidated by new files. If you declared the graph isolating to get faster builds, an incremental build after adding a screen could process only the new file, and you'd end up with a stale or broken graph. That's a much worse bug than a slow build. What you can do is keep the aggregating processor small and not mix per-class generation into it.

One module at a time

KSP processes one module at a time. getSymbolsWithAnnotation only returns symbols from the sources of the module being compiled; dependencies arrive as compiled classes, and a SOURCE-retention annotation no longer exists there. A processor running in :app can't see the screens in :feature:profile.

That's why the design above produces one graph per module. Each module needs its own package and name; if two modules generated the same file in the same package, you'd get a duplicate class error when the app is built. Calling the module graphs from app is still manual, one line per module:

val navController = rememberNavController()

NavHost(navController = navController, startDestination = HomeRoute) {
    homeDestinations(navController)
    profileDestinations(navController)
}

You could automate this as well. KSP can read declarations from the classpath (for example with Resolver.getDeclarationsFromPackage, which is marked @KspExperimental), so a processor in the app module could find marker declarations generated in each feature module. That means a second processor and a naming contract between them. For a handful of feature modules, one line per module is cheaper. The start destination stays with the app too; which screen opens first is not a decision any single feature module should make.

Testing generated code

Generated code is still code, and it needs tests. I'd test it at two levels. First, test the processor on its own with the maintained fork of kotlin-compile-testing, which supports KSP: compile in-memory sources, check the text of the generated file, and check that a screen with an unsupported parameter produces the expected error. Second, have a sample module that really uses the processor and build it in CI, so the generated code compiles against the real Navigation APIs.

It also helps to write the code you want the generator to produce by hand first, and only then teach the processor to produce it. When I moved a project from RxJava to Kotlin Coroutines, the target shape also had to be clear before any mechanical conversion was safe.

Wrapping up

The whole generator is a SymbolProcessor that reads one annotation, a model built from KotlinPoet types, and a FileSpec written as an aggregating output. Within a module, you can no longer forget to register a screen, and screens get their typed route arguments without hand-written toRoute() calls. What stays manual is calling each module's graph from the app and choosing the start destination. The details most worth getting right are the aggregating flag with the originating files, and deferring all screens until every one of them resolves.

Resources

Frequently asked questions

Why use KSP instead of KAPT for annotation processing?
KSP skips the Java stub generation that KAPT needs and resolves types only when a processor asks for them; the Kotlin docs say this makes annotation processing up to about twice as fast. It also understands Kotlin-specific constructs and is read-only: a processor can add new files but never modify your source.
Why does the navigation graph output have to be aggregating?
The graph collects screens from many files into one generated file, and a newly added screen file has to end up in that same file. New files only invalidate aggregating outputs. Declared as isolating, an incremental build could process just the new file and leave you with a stale or broken graph.
Does the generated graph pass typed route arguments to the screens?
Yes, for the convention in this post. A screen parameter of its own route type receives it.toRoute<Route>(), a NavController parameter receives the NavController, and any other parameter makes the processor report an error instead of generating code.
What does SOURCE retention on the Destination annotation mean for the compiled app?
KSP reads the annotation from source code, so it only has to exist during compilation. With SOURCE retention it leaves nothing in the bytecode of the shipped app.

WORK TOGETHER

Let’s start with a good problem.

Looking for an Android engineer for your team, or someone to think through a technical problem with? Let’s talk.

Book a 30-minute conversation[email protected]All contact and podcast links