Home > Back-end >  How to get value of KProperty1
How to get value of KProperty1

Time:12-04

I have an object

I try to get access to field "english"

val englishSentence = dbField::class.declaredMemberProperties.filter { it.name == "english" }[0]

But when I

model.addAttribute("sentence", englishSentence)

I get val com.cyrillihotin.grammartrainer.entity.Sentence.english: kotlin.String

while I expect bla

CodePudding user response:

Do you mean this?

data class Sentence(val id:Int, val english:String, val russian:String)
val dbField = Sentence(1, "blaEng", "blaRus")
val englishProp = dbField::class.declaredMemberProperties.first { it.name == "english" }as KProperty1<Sentence, String>
println(englishProp.get(dbField))

It prints blaEng

CodePudding user response:

You can use the call function on a KProperty to get its value from the object.

val dbField = Sentence(1, "bla-eng", "bla-rus")
val value = dbField::class.declaredMemberProperties.find { it.name == "english" }!!.call(dbField)
println(value)

Output: bla-eng

Remember that data type of value is Any here. You need to cast it manually to the desired data type.

If you want to list all the properties with their values, you can do this:

dbField::class.declaredMemberProperties.forEach {
    println("${it.name} -> ${it.call(dbField)}")
}

Output:

english -> bla-eng
id -> 1
russian -> bla-rus
  • Related