How to copy a two-dimensional array to Kotlin?

This method works just fine. However, I think this does not work.

fun getCopy(array: Array<BooleanArray>): Array<BooleanArray> {
    val copy = Array(array.size) { BooleanArray(array[0].size) { false } }
    for (i in array.indices) {
        for (j in array[i].indices) {
            copy[i][j] = array[i][j]
        }
    }
    return copy
}

Is there a more functional way?

+4
source share
2 answers

You can use clonelike this:

fun Array<BooleanArray>.copy() = map { it.clone() }.toTypedArray()

or if you want to keep some distributions:

fun Array<BooleanArray>.copy() = arrayOfNulls<ByteArray>(size).let { copy ->
    forEachIndexed { i, bytes -> copy[i] = bytes.clone() }
    copy
} as Array<BooleanArray>

or even more concise as suggested by @hotkey :

fun Array<BooleanArray>.copy() = Array(size) { get(it).clone() }
+6
source

How about using copyOf()?

val copyOfArray = array.copyOf()

Returns a new array that is a copy of the original array

Link here

0
source

Source: https://habr.com/ru/post/1660054/


All Articles