I wrote the below code to get a KClass of Array<*>
.
Array::class
However, this code has a compilation error.
Kotlin: Array class literal requires a type argument, please specify one in angle brackets
Do you know the reason or solution?
On the JVM platform, Kotlin Array<T>
types are mapped to Java arrays, which, unlike Java generic types, are not subject to type erasure, they are reified instead.
It means, among other things, that arrays with different element types are represented by different classes, which have different Class<T>
tokens, and these class tokens contain the information about the element type as well. There's no generic array type, but only array types for arrays with different element types.
Since generic Array<T>
doesn't exist, you cannot use its reflection either, you can only get the runtime type information of array types with specified element types:
val c = Array<Int>::class // corresponds to Java Integer[] type
val d = Array<Array<String>>::class // corresponds to Java String[][]
val e = IntArray::class // corresponds to Java int[]
If you need to check whether an arbitrary class is an array type, you can do it with Java reflection:
val c = Array<Int>::class
println(c.java.isArray) // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With