what’s the best practices way to reference a class...
# announcements
m
what’s the best practices way to reference a class’s field dynamically by name? Use reflection?
d
In order of niceness, either polymorphism, a whitelist or reflection depending on your use case.
m
It’s a database row with bunch of states; we want the state column based on other requirements. I suggested perhaps just using a map instead of a data class.
not sure what a “whitelist” is in this context. Looking into reflection, but it looks like it would be more trouble than it’s worth for this case.
d
By whitelist, I mean a map of fieldNames to their accessors.
m
oh oh.
👍🏼
d
You could do,
Copy code
class Row(val map: Map<String, Any>) {
    val columnName: String by map
    val otherColumnName: String by map
}
Typesafe...ish map access.
j
Imho its better to just map the names by hand. This way you can refactor / rename either states in the DB, or in the code and your mapping will continue to work. By using reflection.. you are locked in, or things will fail when the enum is renamed
👍🏼 1
m
Thanks for your input !
Map
it is.