Kotlin: Iterate over components of object

后端 未结 3 1301
长发绾君心
长发绾君心 2020-12-30 20:55

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

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 21:51

    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 = map.toMap()
    }
    
    ...
    ...
    
    
    val someStatistic = DbUsingStat().apply {
      skipped = 5
      removed = 10
      updated = 1505
    }
    
    for((k, v) in someStatistic.asMap())
      println("$k: $v")
    

提交回复
热议问题