本文介绍了Kotlin:遍历对象的组成部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个数据类对象都有每个属性的组件,例如component1,component2等.我想知道Kotlin中是否有任何方法可以迭代类的每个组件.说我上课:

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:

class User(age:Int, name:String)

我能做些什么吗?

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

?

推荐答案

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

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

没有专门用于遍历组件的API,但是您可以使用 Kotlin反射遍历任何类的属性:

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

这篇关于Kotlin:遍历对象的组成部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:27