Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Iterate over components of object

Tags:

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:

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

Could I do something like:

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

?

like image 382
Sermilion Avatar asked Jul 31 '16 20:07

Sermilion


People also ask

How do you iterate through an object in Kotlin?

The for loop is used to iterate over any Kotlin object which can be iterated. We can iterate over an array, collection, string, range, or anything which can be iterated with the help of a for loop.

How do I iterate through a list in Kotlin?

We can use the listIterator() method for iterating through lists in both forward and backward directions.

What is reflection Kotlin?

In Kotlin, Reflection is a combination of language and library capabilities that allow you to introspect a program while it's running. Kotlin reflection is used at runtime to utilize a class and its members, such as properties, methods, and constructors.


2 Answers

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)}")     }   } 
like image 147
yole Avatar answered Sep 29 '22 12:09

yole


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") 
like image 45
Yevhenii Nadtochii Avatar answered Sep 29 '22 11:09

Yevhenii Nadtochii