So after I created lots of enum classes in android (Kotlin), I learnt that enums are not very space efficient in android. So I tried to find another way of doing it. I found the enumerated annotation - @StringDef
. However, Kotlin doesn't seem to support this well and there are no warning or error messages even if I pass something unexpected to a method.
So to clarify what I want to do: I have tons of constant strings that can be classified to different groups (I listed them in different enum class), and when calling some setter functions, I want the caller to choose only from the specific group of things that can be chosen.
For example:
enum class Cat (val breed: String){
AMER_SHORTHAIR("American Shorthair"),
SIAMESE("Siamese");
}
enum class Dog (val breed: String){
GOLDEN_R("Golden Retriever"),
POODLE("Poodle");
}
fun adopt(cat: Cat, dog: Dog){
print("I adopted a "+cat.breed+" and a "+dog.breed)
}
In this case, I can only choose from cats for the first param, and dogs for the second. Is there a way of doing this kind of type-safe methods without using enums?
To avoid using enums, I might need to change the above functionality to:
const val AMER_SHORTHAIR = "American Shorthair"
const val SIAMESE = "Siamese"
const val GOLDEN_R = "Golden Retriever"
const val POODLE = "Poodle"
fun adopt(cat: String, dog: String){...}
This is not ideal since we can get all kinds of typos which happens in our current implementation and is why I switched to enum in the first place. But overall, space consumption > type safe. So if there is no better way, I will need to switch back.
Please let me know if there is any efficient ways to achieve. I've thought about using maps or lists, but indexing or accessing the strings become cumbersome because I need to map the string to themselves (no hard coded strings here except for the first assignment like AMER_SHORTHAIR = "American Shorthair"
).
Thanks.