Home > Net >  Kotlin - Iterate over Class properties
Kotlin - Iterate over Class properties

Time:02-13

Quick question, let's say we have this code:

fun main() {
    val instance = Random(1, "B", 3)
    for(__?__) {
        println(__?__)
    }
}

class Random(
    val A: Int,
    val B: String,
    val C: Int,
) {}

What should I add in places of __?__ so that the program will print out all properities of instance?

CodePudding user response:

You can do this with reflection:

class Random(
  val A: Int,
  val B: String,
  val C: Int,
) {}

val instance = Random(1, "B", 3)

for(field in instance::class.java.declaredFields) {
  field.isAccessible = true
  println(field.name   ": "   field.get(instance).toString())
}

Output:

A: 1
B: B
C: 3

CodePudding user response:

Existing answer provides a solution using Java reflection. Alternatively, we can do this using the Kotlin reflection:

for (prop in Random::class.memberProperties) {
    prop.isAccessible = true
    println("${prop.name} = ${prop.get(instance)}")
}

Kotlin reflection works for multiplatform projects, not only for the JVM target. Also, it understands Kotlin properties, while Java does only recognize fields and methods.

  • Related