I have an interface with a function that has the s...
# announcements
m
I have an interface with a function that has the signature
fun <T: Any?> asArray(tClazz: Class<T>): Array<T>
, how ever, I have no idea how to return an Array of type T in Kotlin on a non-reified function with only the Class as argument.
d
On the JVM:
val array = java.lang.reflect.Array.newInstance(componentType, length)
👍 1
On JS you can use
val array = js("[]").unsafeCast<Array<T>>
(only works if T is not a primitive type)
m
Array<T>()
😄
👎 1
d
That does not work if
T
is not reified.
w
inline fun <reified T: Any?> asArray(tClazz: Class<T>): Array<T> = arrayOf()
Cannot use as
inline
?
m
Thank you @diesieben07! I thought reflection might be the solution, but I could not find out how.
@wbertan No, it is not possible when it is part of an interface.
w
Oh, didn’t know! 😞
m
Arrays are tricky
m
@diesieben07 I get a ClassCastExcpetion tough 🤔
d
Show your code
m
val array: Array<T> = java.lang.reflect.Array.newInstance(tClazz, size) as Array<T>
If I do not cast it, it will just be
Any
and I will be unable to use it for anything.
d
It works for me.
What did you use as
tClazz
?
m
Can I see your code?
Long.
d
If you use primitive types (Int, Short, etc.) you need to ensure to use
Int::class.javaObjectType
. otherwise you will get a
LongArray
, not a
Array<Long>
from
Array.newInstance
m
Aha, I see!
d
You can guard against that inside your
asArray
method:
Copy code
java.lang.reflect.Array.newInstance(cls.kotlin.javaObjectType, 10) as Array<T>
Is there a specific reason you must use an array and not a list? Then you would not need any of this crazyness 😄
m
Yeah, that's what the interface has specified, not my interface 😢 I usually know better than to trying to use generic arrays in Kotlin.
Now it works anyway, thanks a lot @diesieben07! I would not have figured out this one by myself.
Now I just need to guard for this on all primtive types.
I wrote an extension function for this to List. This is the final result https://gist.github.com/mantono/914d54d0c9deb01281ca0133676968a5 once again, huge thanks for the help!
d
You don't need that when, you can just always call javaObjectType
That means you have to guard T by any though: <T : Any>
m
That should be acceptable.
Really nice, thanks 😄