且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Kotlin:遍历对象的组成部分

更新时间:2023-01-11 15:15:01

首先,componentN属性仅适用于数据类,而不适用于每个对象.

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

没有专门用于遍历组件的API,但是您可以使用

There is no API specifically for iterating over the components, but you can use the Kotlin reflection to iterate over properties of any class:

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)}")
    }  
}