I'm observing unexpected behavior with `KClass<...
# reflect
a
I'm observing unexpected behavior with
KClass<*>.declaredMemberProperties
. In the following code example:
Copy code
data class A<T001>(
    val a001:Int?=null,
    val a002:Double?=null,
    val a003:Int?=null,
    val a004:Double?=null,
    val a005:Int?=null,
    var a007:Double?=null,
    val a008:Int?=null,
) {
    var a006: T001? = null
    val a009 = ""
    fun <T002> x() {}
}
A::class.declaredMemberProperties
provides a list of properties in the order
listOf(::a001, ::a002, ::a003, ::a004, ::a005, ::a006, ::a007, ::a008, ::a009)
, whereas at the java level, via
A::class.java.declaredMethods.filter { it.name.startsWith("get") }
, we get the expected order of properties declared in the primary constructor then properties declared in the body. Why does that happen?
v
declaredMethods
returns an array which like a
List
implies that there is a stable ordering.
declaredMemberProperties
returns a
Collection
so you must not rely on the order it returns and whether it returns the order you expect or any other is irrelevant as the error is to expect any particular order. :-)
a
yeah, I got a bit too used to the debugger providing concrete types instead of interface types
e
also note there is no guarantee on reflection order anyway despite the
Array
return type
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getDeclaredMethods-- explicitly says
The elements in the returned array are not sorted and are not in any particular order.
in practice I think you'll get the same results between multiple calls on the same JVM but the API does not even guarantee that
a
Use of
Collection<KCallable>
instead of
List<KCallable>
makes a lot more sense now given the express disclaimer of order on the java side, thanks