Iterate over data class properties without reflection?

I want to traverse a hierarchy tree of data classes to search for nodes that implement a certain interface.

This can be done by writing a function that traverses all known properties for each object type recursively. But this is a lot of code and very fragile, because the moment a new property is added to any of the data classes in the hierarchy, the developer has to remember to add -in the function- an extra check for the new property.

Instead, I would like to iterate through all the properties (like with a generic componentN() list) without prior knowledge of how or which properties are present.

The best solution I found so far is to implement the Iterator interface by all these data classes and use an annotation processor to generate all the boilerplate code. See kotlin - Is there any way to iterate all fields of a data class without using reflection? - Stack Overflow

Is there a way to do this already in Kotlin without using reflection or the library I linked? Otherwise, would it be possible to build this feature as part of the language?

1 Like

Sounds like you want to reinvent reflection.

Reflection can do way more things than just a list of properties and reflection is definitely not performant if you want to iterate over a tree of classes.

When you are talking about performance, you need to do some tests first. Usually, when you need to iterate over methods or properties, reflection performance is not your concern (it is not bad in fact). The only way to use compile-time performance is to use a compiler plugin like it is done in kotlinx.serialization.