Pow*_*mal 6 arrays generics collections kotlin
我做了以下工作:
val genericArray: Array<E> = (genericCollection as java.util.Collection<E>).toArray() as Array<E>
Run Code Online (Sandbox Code Playgroud)
这是正确的方法还是有更优雅的解决方案?
期待您的帮助!
编辑
我最终编写了这个辅助扩展:
fun <E> Collection<E>.toUntypedArray(): Array<E> {
@Suppress("UNCHECKED_CAST")
return arrayOf(size, this) as Array<E>
}
Run Code Online (Sandbox Code Playgroud)
你们中有人有更好的解决方案吗?
Jos*_*hua -2
您不必将其转换为 Java Collection。
fun example () {
val collection: Collection<Int> = listOf()
val typeArray = collection.toTypedArray()
}
fun <T> example2(collection: Collection<T>) {
val typeArray = arrayof(collection)
}
Run Code Online (Sandbox Code Playgroud)