Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple code challenge
// Feel free to run it here try.kotlinlang.org
fun main(args: Array<String>) {
val testCollection = arrayOf(
1, 2, 3,
arrayOf(4, 5, emptyArray<Int>()), null,
arrayOf(emptyArray<Int>(), emptyArray<Int>()),
arrayOf(6)
)
System.out.println("Collection:")
testCollection.forEach { System.out.print("$it ") } // The JVM doesn't print Lists the same way than Arrays
System.out.println("Result:")
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?>) {
nestedList.forEach{
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