Skip to content

Instantly share code, notes, and snippets.

@mantono
Last active October 29, 2019 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mantono/914d54d0c9deb01281ca0133676968a5 to your computer and use it in GitHub Desktop.
Save mantono/914d54d0c9deb01281ca0133676968a5 to your computer and use it in GitHub Desktop.
Convert a List<T> to an Array<T> in Kotlin
@Suppress("UNCHECKED_CAST")
internal fun <T: Any> List<T>.toArray(clazz: Class<T>): Array<T> {
val actualClass: Class<T> = clazz.kotlin.javaObjectType
val array: Array<T> = java.lang.reflect.Array.newInstance(actualClass, size) as Array<T>
this.forEachIndexed { index: Int, obj: T ->
array[index] = obj
}
return array
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment