jeudi 18 mai 2023

How to access the values of a data class in Kotlin?

Here's the codes that is working:

data class Abc(
    val a: String,
    val b: String,
    val c: String,
    val d: D
) {
    data class D(
        val e: String,
        val f: String,
        val g: String
    )
}

fun main() {
    val xx = Abc("a1", "b2", "c3", Abc.D("e4", "f5", "g6"))
    xx::class.memberProperties.forEach {
        if (it.returnType.classifier == String::class) {
            println("${it.name} is a String -> ${it.returnType.classifier == String::class} ")
        }
    }
}

And the output is this:

a is a String -> true 
b is a String -> true 
c is a String -> true 

Now I would like to access the values of each String members and make the output look like this instead:

a is a String -> true -> and the value is a1 
b is a String -> true -> and the value is b2 
c is a String -> true -> and the value is c3 

How should I change the println line? Intuitively I have tried something like:

println("${it.name} is a String -> ${it.returnType.classifier == String::class} -> and the value is ${xx.get(it)}")

but it didn't work ...





Aucun commentaire:

Enregistrer un commentaire