Type-Safe Navigation
Navigation Compose with Serializable Routes
String routes like `"profile/{userId}"` are easy to get wrong. Modern Navigation Compose lets you model destinations as `@Serializable` data classes โ the compiler checks your arguments.
๐ Explanation
Type-safe navigation uses `@Serializable` classes as destinations. `navigate(Profile(userId = id))` replaces hand-built route strings, so a missing or mistyped argument becomes a compile error instead of a runtime crash. `backStackEntry.toRoute<Profile>()` deserializes the arguments back into the original data class, giving you fully typed access without manual `getString` parsing.
Note: Code execution is not available for Android/Kotlin in the browser. Use Android Studio to run and test the app.
import androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport androidx.navigation.toRouteimport kotlinx.serialization.Serializable// 1. Destinations are types, not strings@Serializableobject Home@Serializabledata class Profile(val userId: String)@Composablefun AppNavigation() {val navController = rememberNavController()NavHost(navController = navController, startDestination = Home) {composable<Home> {HomeScreen(onOpenProfile = { id ->// Pass a typed object โ no string formattingnavController.navigate(Profile(userId = id))})}composable<Profile> { backStackEntry ->// Recover the typed arguments safelyval args: Profile = backStackEntry.toRoute()ProfileScreen(userId = args.userId)}}}