Flatten array in Kotlin
Use a more universal flatMap
:
nodes.flatMap {it.asIterable()}
Arrays in Kotlin are invariant so an Array<Array<Node>>
is not an Array<Array<out T>>
(which is the receiver type for flatten
).
It looks like this will be fixed in Kotlin 1.1: Relax generic variance in Array.flatten ยท JetBrains/kotlin@49ea0f5.
Until Kotlin 1.1 is released you can maintain your your own version of flatten
:
/** * Returns a single list of all elements from all arrays in the given array. */fun <T> Array<out Array<out T>>.flatten(): List<T> { val result = ArrayList<T>(sumBy { it.size }) for (element in this) { result.addAll(element) } return result}