https://kotlinlang.org logo
#announcements
Title
# announcements
m

Michael

08/05/2019, 8:28 PM
what’s the best practices way to reference a class’s field dynamically by name? Use reflection?
d

Dominaezzz

08/05/2019, 8:41 PM
In order of niceness, either polymorphism, a whitelist or reflection depending on your use case.
m

Michael

08/05/2019, 8:43 PM
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

Dominaezzz

08/05/2019, 8:45 PM
By whitelist, I mean a map of fieldNames to their accessors.
m

Michael

08/05/2019, 8:46 PM
oh oh.
👍🏼
d

Dominaezzz

08/05/2019, 8:47 PM
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

James Richardson

08/05/2019, 9:10 PM
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

Michael

08/06/2019, 1:20 PM
Thanks for your input !
Map
it is.
4 Views