【发布时间】: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的适当属性值。
标签: android list kotlin properties