How do I create an Array<T> (like Array<S...
# reflect
m
How do I create an Array<T> (like Array<String>, Array<MyClass> etc.) from a List<T>, with the Array actually being the type T, not Array<Any?>? I’m inside an inline function with reified type parameter, so I should know the T KClass, but how do I dynamically create an Array<T>? I tried calling the Array constructor
public inline constructor(size: Int, init: (Int) -> T)
via reflection, but I don’t know how that second parameter is supposed to work.
e
generally can't call
inline
functions with reified type parameters via reflection, and
Array
is even more special, being handled specifically by the compiler
I think your only choice may be to use
Copy code
java.lang.reflect.Array.newInstance(T::class.java, size) as Array<T>
if you can't use
Array<T>(size) {...}
directly
m
I will try that tomorrow, thank you
i
How do I create an Array<T> from a List<T>?
if the type T is known at compile time, you can just use
list.toTypedArray()
e
if you have reified
T
then that works, but so would the
Array()
"constructor" so I assumed Max didn't have that available for some reason
m
The approach with java reflect worked 🙂 I only “know” T as this is a inline function with reified type parameter, I iterate through its props and do this:
Copy code
if(prop.returnClass.java.isArray) {
   val foundGenericType = prop.returnType.arguments.firstOrNull()?.type
   val genericClass = foundGenericType?.classifier as? KClass<*>
   val listVal = (prop as? KProperty1<T, Array<*>?>)?.get(this)?.toList()
   val outputList = // Operate on list instead of array to generate output for reasons
   val array = java.lang.reflect.Array.newInstance(genericClass?.java, outputList.size) as Array<Any?>
     outputList.forEachIndexed { index, any ->
        array[index] = any
     }
  return array
}
So I have a KClass, I would love to be able to do list.toTypedArray<genericClass::asTypeParameter>() 😄