https://kotlinlang.org logo
#reflect
Title
# reflect
d

diesieben07

12/29/2018, 3:09 PM
Mutable/Not-Mutable handling of collection classes seems to be very inconsistent:
Copy code
val x: MutableCollection<String> get() = TODO()
fun main() {
  println(MutableCollection::class) // prints "class kotlin.collections.Collection
  println(Set::class.isSubclassOf(MutableCollection::class)) // prints true, should be false
  println(::foo.returnType) // prints kotlin.collections.MutableCollection<kotlin.String>, yay!
  println(::foo.returnType.classifier) // prints kotlin.collections.Collection, :(
}
Is there any way to figure out if a KType represents a mutable collection type?
g

gildor

12/30/2018, 10:43 AM
There is no such thing as non-mutable collection interface on runtime, it’s compile only thing on JVM, because everything List and MutableList maps on java.lang.List which is mutable This is trade off that required if you want to have 100% interop with Java collections and allow Kotlin do not have own collections implementation
d

diesieben07

12/30/2018, 10:10 PM
I know that part, but it is definitely not purely compile time, as the third example clearly shows.
u

udalov

01/02/2019, 2:40 PM
Right, the information is there, but it seems it's only used in
KType.toString
right now. Therefore, if you have a KType, you can use a dirty workaround of
type.toString().startsWith("kotlin.collections.Mutable")
for now :). If you only have a value of a Kotlin collection, you can use
kotlin.jvm.internal.TypeIntrinsics.isMutableCollection
and others to check if its class extends
MutableCollection
(these methods return true for all foreign (Java) collections, even if they're known to be readonly otherwise) We have plans to make different KClass instances for mutable vs readonly collections: https://youtrack.jetbrains.com/issue/KT-11754
d

diesieben07

01/02/2019, 2:42 PM
Thanks!
3 Views