Create empty array of generic type


#1

What is the best way to create an empty array of a generic type?

This is what I have in Kotlin

private fun <V> createEmptyArray(size: Int): Array<V> {

   [suppress("CAST_NEVER_SUCCEEDS")]
   return arrayOfNulls<Any>(size) as Array<V>
}

Compared to Java

// noinspection unchecked

 
items = (T[])new Object[capacity];

It seems like arrayOfNulls should support any nullable generic type.


#2

First of all, what you are trying to create is not an empty array (which would be an array of length zero), but array full of nulls.

Then, both Java and Kotlin issue a warning on the code you are trying to write for a good reason: since arrays are reified in Java, casting an array of objects to an array of, say, Strings is not safe: passing such a value to a method that expects an array of String will fail. So, what you are trying to achieve is a discouraged, rarely relevant practice, and we are OK with having it a little lengthy.

BTW, Kotlin’s not allowing “arrayOfNulls<V>()” is exactly the same as Java’s not allowing “new V[size]”, because these two are equivalent constructs.


#3

I think I was mistaken thinking that Array<String> was actually Object[] under the hood. In that case it makes sense that there isn't a safe way to make the cast.

Just a couple more questions then:

Are reified generics only supported in inline functions because generic types aren’t kept at runtime?

Is there no safe way to construct an array of a generic type without requiring a factory function?


#4

For the first question: Yes, you are right For the second one: no, there isn't