[英]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.