1

I need to check if any variables inside of my data class are null. To do this I need retrieve them first but I can't access them directly (e.g. myDataClass.name) because I need it to be generic. Is there a way to access these variables without directly naming them. For example, like accessing a member of an array (myArray[0]).

Kamil Kos
  • 35
  • 5
  • This sounds like the [XY problem](http://xyproblem.info/). What are you really trying to achieve? – 9000 Jan 14 '20 at 16:17
  • As stated: retrieve variables from the class dynamically. So something along the lines of myClass.members[0] instead of myClass.name. – Kamil Kos Jan 14 '20 at 16:21
  • The word you were looking for is "reflection": https://kotlinlang.org/docs/reference/reflection.html – 9000 Jan 14 '20 at 16:24

1 Answers1

2

The mechanism you're looking for is called "reflection" and it allows to introspect objects at runtime. You'll find a lot of information on the internet, but just to give you a link you may want to check this answer.

In your case you could do something like this:

data class MyDataClass(
    val first: String?,
    val second: String?,
    val third: Int?
)

fun main() {
    val a = MyDataClass("firstValue", "secondValue", 1)
    val b = MyDataClass("firstValue", null, null)

    printProperties(a)
    printProperties(b)
}

fun printProperties(target: MyDataClass) {
    val properties = target::class.memberProperties
    for (property in properties) {
        val value = property.getter.call(target)
        val propertyName = property.name
        println("$propertyName=$value")
    }
}

Note that for this code to work you must add kotlin-reflect package as a dependency.

user2340612
  • 10,053
  • 4
  • 41
  • 66