mercredi 20 février 2019

Kotlin data class - access property by variable to set it's value

I have a Kotlin data class like this:

data class User(
    var id: Int,
    var name: String? = null,
    var email: String? = null,
    var age: Int? = null,
    var latitude: Float? = null,
    var longitude: Float? = null 
)

Then I create it's instance

var user = User(1)

Then I try this:

val field = "name"
var prop = User::class.memberProperties.find {it -> it.name == field}!!
prop.get(user)

And it works, but if I try to set value like this:

prop.setter.call(user, "Alex")

I get an error:

Unresolved reference: setter

Neither it works like this:

prop.set(user, "Alex")

(This was based on solution provided here, but it isn't work for me: solution )





Aucun commentaire:

Enregistrer un commentaire