Hi! I have this function ``` private fun getFi...
# getting-started
t
Hi! I have this function
Copy code
private fun getFields(): List<KProperty<*>> {
        val kClass = this::class

        return cachedFields.getOrPut(kClass) {
            kClass.declaredMemberProperties
                .filterNot { it.javaField?.isSynthetic == true }
                .onEach { it.isAccessible = true }
                .map { it }
        }
    }
It works fine however, when it retrieves all declared properties it doesn't do them in the order they're declared, example
Copy code
data class Example(val a: String, val b: String)
So b can be gotten before a, is there any way to do this that maintains order that they're declared without using annotations?
y
You could cross reference the property names against the parameter names for the primary constructor and thus obtain the ordering, but that only works if it's a
data
class
t
Yeah that's fine, I only need constructor params
t
Interesting, tysm I'll come back if I need further help 👍
aaandd it worked first try. Updated code if anyone needs reference,
Copy code
return cachedFields.getOrPut(kClass) {
            val p = kClass.primaryConstructor
                ?.parameters
                ?.withIndex()
                ?.map { (index, param) -> param to index }
                ?: error("Primary constructor not found for class ${kClass.simpleName}")

            kClass.declaredMemberProperties
                .filterNot { it.javaField?.isSynthetic == true }
                .onEach { it.isAccessible = true }
                .sortedBy { p.firstOrNull { (param, _) -> param.name == it.name }?.second }
                .map { it }
        }
Thank you so much!
y
Copy code
return cachedFields.getOrPut(kClass) {
            val p = kClass.primaryConstructor
                ?.parameters
                ?: error("Primary constructor not found for class ${kClass.simpleName}")

            kClass.declaredMemberProperties
                .filterNot { it.javaField?.isSynthetic == true }
                .onEach { it.isAccessible = true }
                .sortedBy { p.indexOfFirst { param -> param.name == it.name } }
        }
Cleaned up a little bit!
t
Haha, thank you. There're so many extension functions that I don't know about