0

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 ...

1
  • If you need to loop through the properties, I'd suggest that maybe a class isn't a good fit for your situation; would e.g. a map be better? Reflection might seem attractive if you're used to using it in more dynamic languages; but in Kotlin, it's usually needed only for specific cases such as frameworks, plugins, compiler tools, and interoperability. It's ugly, slow, fragile, insecure, and hard to read, and so it's a strong code smell; there's usually a better approach. Commented May 19, 2023 at 23:28

1 Answer 1

1

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)}")
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I am looking for! Bravo!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.