Bug in Kotlin reflection

It looks like there is a bug in Kotlin reflection.

I am getting List instead of MutableList for property:

val assets: MutableList<AssetDto> = ArrayList()

– for this declaration I am getting List instead of Mutable List via
clazz: KClass<*>
for (prop in clazz.declaredMemberProperties) {
val c = p.returnType.classifier //<-- It gives me kotlin.collections.List instead of MutableList!

}

Is it a bug or what?

P.S. I am now on Kotlin 1.4-M1 - should I upgrade to 1.4 release?

Thanks for information. And yes, It is a bug. – Property type should be available via reflection exactly as it is declared.

I hope Kotlin team will take care of fixing it.

Well no, it’s not a bug. The limitation is intrinsic in the artificial way of separating a mutable collecting from an immutable one when stuff was already existing.

If you need a really immutable collection go for kotlinx.collections.immutable.

1 Like

mutable from readonly. I know this might seem like a small difference but it’s the cause for many bugs and easily confuses newcomers to kotlin. Kotlin’s collections are readonly not immutable.

As you correctly pointed out for immutable collections you should use the library linked above.


Is it a bug? Maybe. There is an argument to be made that kotlin only has mutable/readonly during compile time and that this is just the limitation of the runtime. We would expect returnType.javaType to be the same for List and MutableList. However this is part of the kotlin reflection (not just java reflection) and we actually have a KType which should know the difference between them.
This information is available through the kotlin meatdata annotation so we can expect reflection to know about it.

2 Likes