Kotlin: Iterate over components of object

also, you can use Properties Delegation with built-in delegate 'by map'. it's very useful for some simple stat classes.

class DbUsingStat {
  private val map = mutableMapOf(
    "removed" to 0,
    "updated" to 0,
    "skipped" to 0
  )

  var removed by map
  var updated by map
  var skipped by map

  fun asMap() : Map<String, Int> = map.toMap()
}

...
...


val someStatistic = DbUsingStat().apply {
  skipped = 5
  removed = 10
  updated = 1505
}

for((k, v) in someStatistic.asMap())
  println("$k: $v")

For anyone looking for a reflection-free solution, here is one.

Important: This requires you to be able to modify the User data class.

You can write your own iterator function into the data class, like so:

data class User(age: Int, name: String) {
    operator fun iterator(): Iterator<Pair<String, Any>> {
        return listOf("age" to age, "name" to name)
    }
}

Even though it's a bit of work at first, this allows you to use a for-each style loop like this because Kotlin calls the iterator() function in the background to make for-each loops work:

val aUserObject: User = User(36, "John Doe")
for ((key, value) in aUserObject) {
    println("$key: $value") // age: 36
                            // name: John Doe
}

This keeps your User class a data class and doesn't require the use of Reflection.


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

Tags:

Kotlin