14

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?

2 Answers 2

19

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() }
Sign up to request clarification or add additional context in comments.

1 Comment

Another allocation-efficient implementation: fun Array<BooleanArray>.copy() = Array(size) { get(it).clone() }
-1

What about using copyOf()?

val copyOfArray = array.copyOf()

Returns new array which is a copy of the original array

Reference here

2 Comments

the sample code in the question indicates that a deep copy is required. this code creates a shallow copy.
This keeps references of internal array

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.