Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums or sealed classes with strings

Can I create an enum or a sealed class in Kotlin that contain string resources?

For instance, I have this class:

private enum class Item(
    val id: Int,
    @DrawableRes val imageRes: Int,
    val title: String
) {
    PURSE(1, R.drawable.ic_card, "My balance"),
    MESSAGES(2, R.drawable.ic_bell, "Messages")
}

If I add a field val resources: Resources in the constructor, I cannot set a parameter resources, so cannot use string resources from strings.xml. In this case I cannot use localization for enums.

like image 412
CoolMind Avatar asked Mar 05 '23 09:03

CoolMind


1 Answers

You don't need a Resources instance. You can use a string resource, like you did for the drawable:

private enum class Item(
    val id: Int,
    @DrawableRes val imageRes: Int,
    @StringRes val title: Int
)
like image 74
Tim Avatar answered Mar 17 '23 00:03

Tim