Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 …

>Solution :

KProperty1 has method called call, which takes an instance as argument:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading