I have a two dimensional array of Nodes that I want to flatten into a single array of all nodes using the flatten function of Kotlin arrays.
val nodes = kotlin.Array(width, { width ->
kotlin.Array(height, { height -> Node(width, height) })
})
I then try to call the flatten function on the 2D array
nodes.flatten()
but I get an error: Type mismatch: inferred type is Array<Array<Node>> but Array<Array<out ???>> was expected
. Is there another way I should be doing this?
Arrays in Kotlin are invariant so an
Array<Array<Node>>
is not anArray<Array<out T>>
(which is the receiver type forflatten
).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
: