A function toArray
should convert type-erased list to T
that is Array<String>
now.
inline fun <reified T> toArray(list: List<*>): T {
return list.toTypedArray() as T
}
toArray<Array<String>>(listOf("a", "b", "c")) // should be arrayOf("a", "b", "c")
However, toArray
throws this error.
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
Do you have any ideas?
Problem here, is that you actually trying cast Object[]
to String[]
in terms of Java, or Array<Any>
to Array<String>
in terms of Kotlin, but this is different objects.
So, this statement:
list.toTypedArray()
returns Array<Any?>
, and then you trying to cast it to Array<String>
and get ClassCastException
.
I suggest pass type parameter itself, and cast List
:
inline fun <reified T> toArray(list: List<*>): Array<T> {
return (list as List<T>).toTypedArray()
}
toArray<String>(listOf("1", "2"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With