How to get a KClass array?

I wrote the code below to get KClass Array<*> .

 Array::class 

However, this code has a compilation error.

Kotlin: array class literal requires type argument, specify one in angle brackets

Do you know a reason or solution?

+5
source share
1 answer

On the Kotlin Array<T> JVM platform, types are mapped to Java Arrays , which, unlike Java generic types, cannot be erased , they are reified .

This means, among other things, that arrays with different types of elements are represented by different classes that have different Class<T> tokens, and these class tokens also contain information about the type of element. There is no general array type, but only array types for arrays with different types of elements.

Since the common Array<T> does not exist, you also cannot use its reflection, you can get information such as the runtime of array types with the 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 if an arbitrary class is an array type, you can do this with Java reflection:

 val c = Array<Int>::class println(c.java.isArray) // true 
+8
source

Source: https://habr.com/ru/post/1261448/


All Articles