Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

460
Visualizações
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 )

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

memberProperties returns a Collection<KProperty1<T, *>>, but you need KMutableProperty1. So

if (prop is KMutableProperty1) {
    (prop as KMutableProperty1<T, Any>).set(user, "Alex")
} else { 
    // what do you want to do if the property is immutable?
}

The cast is needed because the smart cast would only give you a KMutableProperty1<T, *> and you couldn't call set anyway because the compiler doesn't know what type to accept as its second parameter.

over 4 years ago · Santiago Trujillo Relatório

0

when you got the instance of your object needed, you simply do -> user.name = "toto"

over 4 years ago · Santiago Trujillo Relatório

0

You can use Java-style reflection if you're targeting the JVM platform. To set the "name" property of the user instance of the class User to "Alex",

val field = "name"
user.javaClass
    .getMethod("set${field.capitalize()}", String::class.java)
    .invoke(user, "Alex")

And to get the "name" property,

val userName = user.javaClass
    .getMethod("get${field.capitalize()}")
    .invoke(user) as String
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda