更新时间:2023-01-11 15:15:01
首先,componentN
属性仅适用于数据类,而不适用于每个对象.
First of all, the componentN
properties are available only on data classes, not on every object.
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)}")
}
}