繁体   English   中英

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

[英]Haw to use variable instead of real property name to describe property 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?

如果您的类没有代码更改,则只能通过反射 API 进行。 通常不推荐,因为它可能更慢,并且更容易出错。

有关如何使用反射来实现这一目标的示例,请参阅此答案: https : //stackoverflow.com/a/35539628/3801327

我建议您改用 CommonsWare 在评论中建议的解决方案(添加 get 运算符)

暂无
暂无

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

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