How to copy a two-dimensional array in Kotlin?

2019-06-17 08:23发布

问题:

This method works fine. However, I think it is not functional.

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?

回答1:

You can make use of clone like so:

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

or if you'd like to save some allocations:

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() }


回答2:

What about using copyOf()?

val copyOfArray = array.copyOf()

Returns new array which is a copy of the original array

Reference here



标签: arrays kotlin