13

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?

mmorihiro
  • 857
  • 2
  • 13
  • 17

2 Answers2

17

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() }
miensol
  • 39,733
  • 7
  • 116
  • 112
  • 8
    Another allocation-efficient implementation: `fun Array.copy() = Array(size) { get(it).clone() }` – hotkey Nov 07 '16 at 12:24
-1

What about using copyOf()?

val copyOfArray = array.copyOf()

Returns new array which is a copy of the original array

Reference here

mxcoder
  • 7
  • 2