[英]Why use "sealed class" and make object in Navigation? (Kotlin Jetpack Compose)
I've heard the most popular way to define screen and route is to use sealed class我听说定义屏幕和路由的最流行的方法是使用密封类
But I can't understand intuitively that way.但我不能这样直观地理解。
first is Why use sealed class .首先是为什么使用密封类。 there are other classes including just the default class.还有其他类,包括默认类。
The second is Why use object in sealed class.第二个是为什么在密封类中使用对象。
I think the second question is have a relation to a singleton.我认为第二个问题与单身人士有关。 But why screen should be a singleton?但是为什么 screen 应该是一个单例呢?
this is code what I've seen这是我看到的代码
sealed class Screen(val route: String) {
object Home: Screen(route = "home_screen")
object Detail: Screen(route = "detail_screen")
}
sealed class is a good choice when you have routes with arguments , like shown in Jetcaster Compose sample app:当您有带参数的路由时,密封类是一个不错的选择,如Jetaster Compose 示例应用程序中所示:
sealed class Screen(val route: String) {
object Home : Screen("home")
object Player : Screen("player/{episodeUri}") {
fun createRoute(episodeUri: String) = "player/$episodeUri"
}
}
In case when you don't have arguments in any of your routes, you can use enum class instead, like shown in Owl Compose sample app:如果您的任何路由中都没有参数,则可以改用枚举类,如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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.