Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a type-erased list to an array in Kotlin?

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?

like image 642
mmorihiro Avatar asked Sep 04 '25 17:09

mmorihiro


1 Answers

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.

How to fix?

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"))
like image 87
Ruslan Avatar answered Sep 07 '25 12:09

Ruslan