【问题标题】:Haw to use variable instead of real property name to describe property in Kotlin如何使用变量而不是真实属性名称来描述 Kotlin 中的属性
【发布时间】:2020-11-04 23:18:47
【问题描述】:

有很多类似的问题,但我仍然找不到正确的答案。 我认为在 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?

【问题讨论】:

  • “我认为在爪哇方括号中有效”——不,抱歉。 “在 KOTLIN 中是否可以进行这样的构建?” -- 如果将fun get(key: String) { ... } 添加到source 类中,则可以使用source[variable]。您的 get() 函数将负责返回给定提供的 key 的适当属性值。
  • 这能回答你的问题吗? Accessing dynamically to a Kotlin class property

标签: android list kotlin properties


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    相关资源
    最近更新 更多