Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A simple code challenge
// Feel free to run it here
fun main(args: Array<String>) {
val testCollection = arrayOf(
1, 2, 3,
arrayOf(4, 5, emptyArray<Int>()), null,
arrayOf(emptyArray<Int>(), emptyArray<Int>()),
testCollection.forEach { System.out.print("$it ") } // The JVM doesn't print Lists the same way than Arrays
testCollection.flattenArray().forEach { System.out.print("$it ") }
fun <T: Any?> Array<T>.flattenArray(): Array<*> {
// Easier to handle a mutable list than an array
val flatList = mutableListOf<Any?>()
flattenArray(this, flatList)
return flatList.toTypedArray()
private fun <T: Any?> Array<T>.flattenArray(nestedList: Array<*>, flatList: MutableList<Any?>) {
e -> when(e){
!is Array<*> -> flatList.add(e)
else -> flattenArray(e, flatList)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment