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?
Copying Arrays Using arraycopy() method src - source array you want to copy. srcPos - starting position (index) in the source array. dest - destination array where elements will be copied from the source. destPos - starting position (index) in the destination array.
This article explores different ways to copy all elements of an int array into a new array in Kotlin... The `copyOf()` function returns a new array, a copy of the original array, resized to the given size. To copy the complete array, pass the original array's length to the `copyOf()` function. TECHIE DELIGHT </> Ace your Coding Interview
This article covers different ways to declare and initialize two-dimensional arrays in Kotlin. 1. Using arrayOf()function. The most common way to declare and initialize arrays in Kotlin is the arrayOf()function. To get a two-dimensional array, each argument to the arrayOf()function should be a single dimensional array.
The resultant array is called a jagged array, whose elements can have different dimensions and sizes. Following is a simple example demonstrating the jagged arrays: This will result in the following two-dimensional ragged array: That’s all about declaring and initializing a two-dimensional array in Kotlin. Average rating 4.83 /5.
In Kotlin, you can squeeze the above method to the following single line of code: By definition, apply accepts a function, and sets its scope to that of the object on which apply has been invoked. This means that no explicit reference to the object is needed. Apply () can do much more than simply setting properties of course.
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() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With