简体   繁体   中英

Haw to use variable instead of real property name to describe property in Kotlin

There are a lot of similar questions, but I still can't find out right answer. In Jawa square brackets works i think, but in Kotlin?

data class source (
val npk : Int = 0,
val name : String = "",
val coa : String = ""
)

fun main() {
  var sourceList : MutableList<source> = mutableListOf(source(1, "Uno", "one"),
                                                       source(2, "Dues", "two"),
                                                       source(3, "Tres", "three"))
   sourceList.forEach { source -> println(source.name)} // haw to use variable instead "name"?
      val variable = "name"
 //  sourceList.forEach { source -> println(source.$variable)} Is there construction like this possible in KOTLIN?

Without code changes on your class it's only possible via reflection API. Not usually recommended as it can be slower, and is more error prone.

See this answer for an example on how reflection can be used to achieve that : https://stackoverflow.com/a/35539628/3801327

I'd recommend you to go with the solution that CommonsWare suggested in the comment ( adding get operator ) instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM