is there any way to create an empty array of a gen...
# announcements
t
is there any way to create an empty array of a generic type?
a
Generic type unknown at compile-time?
s
you may have to reify your generic type and inline the function in question
Copy code
inline fun <reified T> emptyGenericArray(): Array<T> {
  return arrayOf()
}
b
maybe this?
Copy code
inline fun <reified T> genericArrayOf() : Array<T> = arrayOf()
oh sorry LOL
👍 1
t
not possible. The method is a class method so it can not be reified. Basically I have to implement an interface of the sort
fun <A : Something> foo(bar: Class<A>): Array<A>
a
If the empty array is an immutable placeholder, you can look at the empty array implementation in kotlin: https://github.com/JetBrains/kotlin/blob/1.2.60/core/builtins/src/kotlin/ArrayIntrinsics.kt#L24 You can sort of cast an empty array for any type
k
that's what i said & deleted, since the exact same problem occurs at the
arrayOfNulls<T>(0)
call,
T
is again not reified
t
It's probably not supposed to be immutable. "The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers." Tbh I have no idea how anyone is supposed to implement this
god I hate the JVM
k
if it's empty, there is nothing to modify, it'll always be immutable
t
there's
fun <T> Array<T>.plus(element: T): Array<T>
though and if I return an
arrayOfNulls<Any?>(0) as Array<T>
than calling that method on it will fail
k
the
plus
function already contains the type in
this
(being an
Array<T>
), if you're confused as to why it's not reified
t
I'm just saying there is no way I can create an empty
Array<T>
for any T
even
arrayOfNulls<Any?>(0) as Array<SomeClass?>
already doesn't work 😕
k
i'm trying but i cant even find something hacky. deeper issue is the bad method signature, because like you say, you can't just magically pull a typed array out of your ass
b
Well, it would be good if you could use list instead of array
Copy code
fun <T : Any> genericListOf() : List<T> = arrayOf<KClass<T>>().mapNotNull { it.objectInstance }
Do you know any solution like that to arrays?
k
i do not recomend using it, but i found this
Copy code
override fun <T : Something> foo(bar: Class<T>): Array<T>
    = java.lang.reflect.Array.newInstance(bar, 0) as Array<T>
d
java.lang.reflect.Array.newInstance
is the way to go if you need this. It's ugly but perfectly fine to use.
t
Thx that looks like it might work. The method probably isn't gonna be called often so reflection shouldn't be a problem
d
It's a JVM intrinsic, it's not much slower than just creating a new array the "normal way".