https://kotlinlang.org logo
#compose
Title
# compose
j

jaqxues

11/01/2020, 9:13 AM
Is there any reason not to use Enums instead of sealed classes for defining screens? (https://developer.android.com/jetpack/compose/navigation#bottom-nav)
m

msfjarvis

11/01/2020, 10:16 AM
Not necessarily, no.
j

jaqxues

11/01/2020, 10:17 AM
It does make your life easier if you use a Drawer for example and you can just use
.values()
on an enum to create a Drawer Entry for every screen.
k

kingsley

11/01/2020, 12:33 PM
I believe it’s a case by case basis. If you wouldn’t need to pass extra parameters, e.g
DetailScreen(itemId = XXX)
, then sure enum might just be enough And by the way, if necessary, you could access all subclasses via
SealedClassType::class.sealedSubclasses
j

jaqxues

11/01/2020, 12:37 PM
Yes I kind of broke Kotlin while experimenting
Copy code
sealed class LocalScreen(val route: String, @StringRes val name: Int, private val _icon: Any) {
    object Home : LocalScreen("home", R.string.menu_home, Icons.Default.Home)
    object Settings : LocalScreen("settings", R.string.menu_settings, Icons.Default.Settings)
    object Support :
        LocalScreen("support", R.string.menu_support, R.drawable.ic_support_agent_black_48dp)

    object AboutUs : LocalScreen("about_us", R.string.menu_about_us, R.drawable.ic_group_black_48dp)
    object Shop : LocalScreen("shop", R.string.menu_shop, R.drawable.ic_payment_black_48dp)
    object Legal : LocalScreen("legal", R.string.menu_legal, <http://Icons.Default.Info|Icons.Default.Info>)

    init {
        check(_icon is VectorAsset || _icon is @DrawableRes Int) {
            "Unknown Type for Icon ${_icon::javaClass.name} (${_icon})"
        }
    }

    @Composable
    val icon: VectorAsset
        get() {
            return when (_icon) {
                is VectorAsset -> _icon
                is @DrawableRes Int -> vectorResource(_icon)
                else -> error("Unknown Type for Icon")
            }
        }

    companion object {
        val displayable =
            arrayOf(Home, Setting, Support, AboutUs, Shop, Features, Legal)
    }
}
println(LocalScreens.displayable.contentDeepToString())
Outputs
Copy code
[null, com.jaqxues...$Settings@8af1db0, ...]
Somehow Home is null, when i use it in compose