Incidentally, I have an Enumeration<String>
in Kotlin. It contains toList()
, but I need to convert it to an Array<String>
.
What is the best way to do this in Kotlin?
CodePudding user response:
Lists can be converted to arrays via the .toTypeArray
function:
val myEnumeration: Enumeration<String> = ...
val array = myEnumeration.toList().toTypedArray() // array is Array<String>
A simple extension function as a shortcut is also trivial:
inline fun <reified T> java.util.Enumeration<T>.toTypedArray(): Array<T> = toList().toTypedArray()
The reason toTypedArray()
doesn't work directly on an Enumeration is that it needs a Collection<T>
to be able to efficiently instantiate the new array, but going through toList()
first is still efficient enough for most scenarios.