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?
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() }
What about using copyOf()
?
val copyOfArray = array.copyOf()
Returns new array which is a copy of the original array
Reference here