Kotlin: general collection into a common array

How to get a generic array from a generic collection ?

I have done the following:

val genericArray: Array<E> = (genericCollection as java.util.Collection<E>).toArray() as Array<E>

Is this right, or is there a more elegant solution?

Looking forward to your help!

EDIT

I ended up writing this helper extension:

fun <E> Collection<E>.toUntypedArray(): Array<E> {
    @Suppress("UNCHECKED_CAST")
    return arrayOf(size, this) as Array<E>
}

Do any of you have a better solution to this problem?

+4
source share
1 answer

You do not need to throw it in the Java Collection.

fun example () {
    val collection: Collection<Int> = listOf()
    val typeArray = collection.toTypedArray()
}

fun <T> example2(collection: Collection<T>) {
    val typeArray = arrayof(collection)
}
0
source

Source: https://habr.com/ru/post/1686194/


All Articles