Kotlin:通用阵列的通用集合

时间:2022-06-07 21:18:28

How to get a generic array out of a generic collection?

如何从泛型集合中获取通用数组?

I have done the following:

我做了以下事情:

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

Is this the right way to go 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>
}

Does anyone of you have a better solution for this problem?

你们中有谁有更好的解决方案吗?

1 个解决方案

#1


0  

You don't have to cast it to Java Collection.

您不必将其强制转换为Java Collection。

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

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

#1


0  

You don't have to cast it to Java Collection.

您不必将其强制转换为Java Collection。

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

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