为什么使用“密封类”并在导航中创建对象?(Kotlin Jetpack 撰写)

Sue*_*e97 11 kotlin android-navigation android-jetpack-compose

我听说定义屏幕和路由的最流行的方法是使用密封类
,但我无法直观地理解这种方式。

首先是为什么使用密封类。还有其他类,包括默认类。

第二个问题是为什么在密封类中使用对象。
我认为第二个问题与单身人士有关。但为什么 screen 应该是单例呢?

这是我所看到的代码

sealed class Screen(val route: String) {
    object Home: Screen(route = "home_screen")
    object Detail: Screen(route = "detail_screen")
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*hov 15

当您有带有参数的路由时,密封类是一个不错的选择,如Jetcaster Compose 示例应用程序中所示:

sealed class Screen(val route: String) {
    object Home : Screen("home")
    object Player : Screen("player/{episodeUri}") {
        fun createRoute(episodeUri: String) = "player/$episodeUri"
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您的任何路由中都没有参数,则可以使用枚举类,如Owl Compose 示例应用程序中所示:

enum class CourseTabs(
    @StringRes val title: Int,
    @DrawableRes val icon: Int,
    val route: String
) {
    MY_COURSES(R.string.my_courses, R.drawable.ic_grain, CoursesDestinations.MY_COURSES_ROUTE),
    FEATURED(R.string.featured, R.drawable.ic_featured, CoursesDestinations.FEATURED_ROUTE),
    SEARCH(R.string.search, R.drawable.ic_search, CoursesDestinations.SEARCH_COURSES_ROUTE)
}
Run Code Online (Sandbox Code Playgroud)