Search code examples
javakotlinreflectionfunctional-programming

Iterate over Java class hierarchy using functional programming


Considering this piece of Kotlin code, that collects all declared fields in superclass hierarchy, is there way to write it using functional programming?

var scanClass: Class<*>? = someClass

val fields = mutableListOf<Field>()
while (scanClass != null) {
    fields += scanClass.declaredFields
    scanClass = scanClass.superclass
}

Solution

  • Yes, you can write the same code using functional programming in Kotlin by using a sequence of classes generated by iteratively taking the superclass of the current class. Here's an example:

    val fields = generateSequence(someClass) { it.superclass }
    .flatMap { it.declaredFields.asSequence() }
    .toList()
    

    In this code, the generateSequence function generates a sequence of classes, starting with someClass and then iteratively taking its superclass. The flatMap function is used to flatten the sequence of arrays of fields into a single sequence of fields. Finally, the toList function collects the elements of the sequence into a list.