简体   繁体   English

在 Kotlin 中使用变量而不是真实的属性名称来描述属性

[英]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?我认为在 Jawa 方括号中有效,但在 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.如果您的类没有代码更改,则只能通过反射 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有关如何使用反射来实现这一目标的示例,请参阅此答案: 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我建议您改用 CommonsWare 在评论中建议的解决方案(添加 get 运算符)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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