11

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?

2
  • Specify your error more precisely, use the original error message. Commented Jan 4, 2017 at 16:40
  • added the actual error message Commented Jan 4, 2017 at 16:47

2 Answers 2

23

Use a more universal flatMap:

nodes.flatMap {it.asIterable()}
Sign up to request clarification or add additional context in comments.

Comments

10

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
}

1 Comment

For the record, the same flatten method applies to lists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.