https://kotlinlang.org logo
#feed
Title
# feed
x

xxfast

05/18/2022, 3:20 PM
Is your server sending 🍌 when you were expecting 🍎and 🍊? Here's a tale of unconfined enums in kotlin https://link.medium.com/v9MoWVdk8pb
e

ephemient

05/18/2022, 3:36 PM
my preferred approach is more like
Copy code
value class Fruit(val name: String) {
    @StringRes val stringRes: Int
        get() = when (this) {
            Apple -> R.string.fruit_apple
            else -> 0
        }

    companion object {
        val Apple = Fruit("Apple")
    }
}
but YMMV
🙌 1
x

xxfast

05/18/2022, 8:31 PM
How would the use-site look? There wouldn't be any exhaustion checks at compile time right?
e

ephemient

05/19/2022, 5:04 AM
no exhaustion checks because the type is non exhaustive, but most use sites look similar to enums by defining the known values as companion object members
for this case I'd define another
Copy code
fun Fruit.getLocalizedName(resources: Resources): String {
    val id = stringRes
    return if (id != Resources.ID_NULL) resources.getString(id) else name
}
to avoid having to write that check in multiple places though
x

xxfast

05/19/2022, 7:51 AM
the interface approach lets you have some exhaustive type checks, and its nice that you can still safely enumerate over possible values when there's a whole hierarchy of em.
Copy code
@Composable
fun FruitView(fruit: Fruit) {
  when (fruit) {
    is Pome -> when (fruit) {
      Apple -> AppleView(fruit)
      Pears -> PearView(fruit)
      Quince -> QuinceView(fruit)
    }
    
    is Citrus -> when(fruit){
      Oranges -> OrangeView(fruit)
      Lime -> LimeView(fruit)
      Lemon -> LemonView(fruit)
    }

    else -> OtherFruitView(fruit.name)
  }
}
p.s mind the nested whens here
4 Views