Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a KClass of Array?

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?

like image 329
mmorihiro Avatar asked Dec 18 '16 09:12

mmorihiro


1 Answers

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
like image 57
hotkey Avatar answered Sep 30 '22 17:09

hotkey