In Navigation Compose, how do type-safe routes work with @Serializable route classes, composable<T>() and toRoute(), and what do they replace?
answer
- Kotlin Serialization plugin
- object for no arguments, class for some
- rebuilt from the back stack entry
- custom types need a typeMap
basics
~10 sSince Navigation 2.8.0, each destination is a @Serializable object or data class. You register it with composable<T>(), navigate with navController.navigate(ProductDetail(id)), and rebuild the arguments with backStackEntry.toRoute<T>(), replacing string routes and navArgument lists.
solid answer
~40 sType-safe routes arrived in Navigation 2.8.0 and use the Kotlin Serialization plugin. A route without arguments is a `@Serializable object` (`Home`); one with arguments is a `@Serializable data class` (`ProductDetail(val id: String)`). In the `NavHost` you register `composable<ProductDetail> { entry -> val route = entry.toRoute<ProductDetail>() }`, and you navigate with `navController.navigate(ProductDetail(id))`, so the compiler checks every argument's name and type. This replaces string routes such as `"product/{id}"` plus `navArgument` declarations and manual parsing. Primitives, strings, enums, nullable primitives and lists of `Int`, `String`, `Boolean`, `Float` and `Long` work out of the box; a custom class argument needs a `NavType` in `typeMap`, or building the graph fails with an `IllegalArgumentException`. Pass ids, not whole objects: arguments live in saved state, whose size is limited.
go deeper
Recall the three pieces: a @Serializable route class, composable<T>() in the NavHost, and navigate(Route(args)) with toRoute() to read them back.
Explain how the serializer becomes a route pattern, path vs query arguments, the built-in types, and why a custom type needs a NavType in typeMap.
Judge what goes into a route: ids rather than objects, events instead of passing NavController down, and the runtime failures type safety does not remove.
Decide how route classes are shared across modules and versioned, since they become the contract every feature compiles against.
## What a route is In Navigation Compose a **route** identifies a destination and carries the data it needs. Before Navigation 2.8.0, routes were strings: you wrote `composable("product/{id}", arguments = listOf(navArgument("id") { type = NavType.StringType }))`, navigated with `navController.navigate("product/$id")`, and read `backStackEntry.arguments?.getString("id")`. A typo in the pattern or a wrong type surfaced only at runtime. **Navigation 2.8.0** added type safety to the Kotlin DSL that Navigation Compose uses. A route is now any serializable type: - **an `object`** for a destination without arguments; - **a `class` or `data class`** for a destination with arguments; - **a `KClass`** (`ProductDetail::class`) where you only need to name the type. All of them must be annotated **`@Serializable`**, which needs the Kotlin Serialization compiler plugin (`org.jetbrains.kotlin.plugin.serialization`) in the module that declares them. ```kotlin @Serializable object Home @Serializable data class ProductDetail(val id: String, val fromSearch: Boolean = false) NavHost(navController, startDestination = Home) { composable<Home> { HomeScreen(onOpenProduct = { id -> navController.navigate(ProductDetail(id)) }) } composable<ProductDetail> { entry -> val route: ProductDetail = entry.toRoute() ProductDetailScreen(route.id) } } ``` ## How it works underneath The serialization plugin generates a serializer for each route class. Navigation reads its descriptor and builds a route pattern from it, starting with the class's serial name: 1. **Required arguments** (no default value) become **path** segments. 2. **Arguments with a default value**, and collection arguments, become **query** parameters, so they are optional. `navigate(ProductDetail("p-42"))` encodes the instance into that pattern; **`NavBackStackEntry.toRoute<T>()`** decodes the entry's arguments back into an instance. In a `ViewModel`, `SavedStateHandle.toRoute<T>()` does the same from the handle the destination's `ViewModel` receives. ## Supported argument types | Argument type | Works out of the box? | |---|---| | `Int`, `Long`, `Float`, `Boolean`, `String` | yes | | nullable versions such as `Int?` | yes | | enums | yes | | lists of `Int`, `String`, `Boolean`, `Float`, `Long` | yes | | value classes | yes, since 2.9.0 | | your own class, such as `Filter` | no: supply a `NavType` in `typeMap` | For a custom type you write a `NavType<Filter>` and pass `typeMap = mapOf(typeOf<Filter>() to FilterNavType)` to `composable<T>()`, and to `SavedStateHandle.toRoute` when a `ViewModel` reads the route. Without it, building the graph throws an `IllegalArgumentException`: "Route ... could not find any NavType for argument ...". So type safety checks your call sites at compile time, but a missing `NavType` is still a runtime failure when the graph is built. ## What the API asks of you - **Pass ids, not objects.** Arguments are kept in the back stack's saved state, and the total space for saved state is limited on Android. Pass `ProductDetail(id)`; let the destination load the product. Large or complex data in arguments is discouraged by the guide for that reason and because it goes stale. - **Navigate from callbacks.** Call `navigate()` in an event handler, never in the composable body, or it runs on every recomposition. - **Do not hand `NavController` to screens.** Expose `onOpenProduct: (String) -> Unit` and let the `NavHost` call `navigate`, which keeps screens reusable and previewable. - **Check the current destination by type.** `destination.hasRoute<ProductDetail>()` replaces comparing route strings. ## Mistakes that still compile Type safety removes typos in route strings, but several mistakes still compile and fail later: - **Forgetting the serialization plugin** in the module that declares a route. The annotation is then only a marker, no serializer is generated, and the app fails at runtime when Navigation looks for one. - **Navigating to a route that no destination registers**, for example a route class from a feature graph that was never added to this `NavHost`. `navigate()` throws an `IllegalArgumentException` saying that no navigation destination matching the route can be found in the navigation graph. - **Navigating with mutable or large objects.** Even when a custom `NavType` makes it possible, the copy in the back stack goes stale as soon as the source changes. - **Reading the route in the wrong place.** Read it once with `toRoute()` in the destination lambda or with `SavedStateHandle.toRoute()` in the `ViewModel`, and pass plain values down to the screen. ## Version notes - **2.8.0**: type-safe Kotlin DSL and Navigation Compose; built-in list and nullable types. - **2.9.0**: non-reified overloads that take a `KClass`, and value classes as routes or arguments. - **2.10.x** (2.10.2 current): no change to the route model. Fragment destinations in XML graphs use Safe Args instead; that path is outside this answer.
- With Navigation Compose type-safe routes, which arguments become path segments and which become query parameters?Navigation builds the pattern from the route class's serializer. A property without a default value is required and becomes a path segment; a property with a default value, or a collection, becomes a query parameter and is optional. That is why `ProductDetail(id)` can omit `fromSearch` when it has a default.
- Your route has a Filter data class argument and the app crashes when the NavHost is built. What is missing?Navigation has no built-in `NavType` for your own class, so building the graph throws `IllegalArgumentException` saying it could not find any NavType for the argument. Write a `NavType<Filter>` that serializes it and pass `typeMap = mapOf(typeOf<Filter>() to FilterNavType)` to `composable<T>()`. Often the better fix is to pass a filter id instead.
- Type-safe routes need the Safe Args Gradle plugin in a Compose app
- Any data class works as an argument without extra setup
- Type-safe routes make every navigation error a compile-time error
- It is fine to pass the whole product object as a route argument
- toRoute() is only available inside a ViewModel
Assumes Navigation Compose 2.10.2 alongside Compose 1.12; type-safe routes exist since Navigation 2.8.0, and value-class arguments since 2.9.0.