Each data class object has a component for each property like component1, component2, etc.. I was wondering if there is any way in Kotlin to iterate over each component of a class. Say I have class:

data class User(age:Int, name:String)

Could I do something like:

for(component in aUserObject){
    //do some stuff with age or name
}

?

推荐答案

First of all, the componentN properties are available only on data classes, not on every object.

没有专门用于迭代组件的API,但您可以使用Kotlin reflection来迭代任何类的属性:

class User(val age: Int, val name: String)

fun main(args: Array<String>) {
    val user = User(25, "Bob")
    for (prop in User::class.memberProperties) {
        println("${prop.name} = ${prop.get(user)}")
    }  
}

Kotlin相关问答推荐

Kotlin和JavaFX:绑定行为奇怪

插入/更新/upsert时不发出房间流

映射中列表类型的Kotlin可空接收器?

KMP:未能添加cafe.adriel.voyager依赖项

如何更改默认推断没有接收者的函数类型?

列表在 android WebView 中没有正确迭代

Kotlin 接口类型参数

如何在 Jetpack Compose 中启动和停止动画

为什么 trySend 会发出假数据?

Kotlin 插件之间的区别

如何从 kotlin 中的数据类访问 val?

Kotlin 中多个 init 块的用例?

Kotlin 中的部分类委托

作为 Kotlin 中的函数的结果,如何从 Firestore 数据库返回列表?

如何暂停kotlin coroutine直到收到通知

类型不匹配:推断类型为 LoginActivity 但应为 LifecycleOwner

在 Kotlin 函数上使用 Mokito anyObject() 时,指定为非 null 的参数为 null

类型不匹配推断类型为单位,但应为空

Kotlin数据类打包

尾随 lambda 语法(Kotlin)的目的是什么?