So here’s the problem, I have some map structure and I need string keys which aren’t hardcoded in and easily readable. Their underlying value also doesn’t really matter (except for readability) and they should preferably be compile time constants.
Sounds like an enum should be the perfect thing for this right? But if I want to use an enum I would have to do something like
enum class Keys {
key1Name,
key2Name…
}
But if I actually wanted to use it as a key lets say for an android studio intent I would do
intent.putExtras(Keys.key1Name.name, var1Value)
Put using name property like that enums reduces readability and it seems like thats the kind of ugly code that kotlin tries to get ride of. Also that would make the key to not be a compile-time constant (not a huge issue but still).
I usually just instead use an object with const strings but then it looks like this
object Keys {
const val key1Name = “key1Name”
const val key2Name = “key2Name”…
}
But again thats even boilerplatey but at least its only boilerplatey in a part of the codebase that nobody is gonna really look at so it seems better to me. And more to the point, isn’t the whole point of enums is to not have to do things like that?
So what I propose is some kind of string enum where the enum values would actually be replaced with their names as string like how C enum values are replaced by a number. So the syntax might look something like this
enum string Keys {
key1Name,
key2Name…
}
println(Keys.key1Name) //prints key1Name
println(Keys.key2Name) //prints key2Name
Maybe this might just be a super specific problem that it would be overkill to introduce something like this and maybe I’m just inexperienced but map structures seem extremely common and there just doesn’t seem like a good syntax to make keys for them with kotlin currently.
Also having the same thing with intergers like this thread suggests would be nice.
Edit: My solution probably isn’t very good but I still think that there could be some kind of syntactical sugar added to improve using keys for this type of thing, any ideas?