Create a shallow copy of an array in Kotlin
This article explores different ways to clone an array in Kotlin.
The solution should create a shallow copy of the array, i.e., the new array can reference the same elements as the source array. If the array contains any reference elements, they are copied as well.
1. Using clone() function
The standard solution for copying arrays in Kotlin is using the extension function clone(), which creates a shallow copy of the array.
|
1 2 3 4 5 6 7 |
fun main() { val src = arrayOf<Int?>(1, 2, 3, 4, 5) val dest = src.clone(); println(dest.contentToString()) // [1, 2, 3, 4, 5] } |
2. Using System.arraycopy() function
Alternatively, you can use the System.arraycopy() function, which also creates a shallow copy of the array.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <T> copyArray(src: Array<T>, dest: Array<T>) { System.arraycopy(src, 0, dest, 0, src.size) } fun main() { val src = arrayOf<Int?>(1, 2, 3, 4, 5) val dest = arrayOfNulls<Int>(src.size) copyArray(src, dest) println(dest.contentToString()) // [1, 2, 3, 4, 5] } |
3. Using copyOf() function
The copyOf() function returns a new array, a copy of the original array, resized to the given size.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun <T> copyArray(src: Array<T>): Array<T?> { return src.copyOf(src.size) } fun main() { val src = arrayOf<Int?>(1, 2, 3, 4, 5) val dest = copyArray(src) println(dest.contentToString()) // [1, 2, 3, 4, 5] } |
4. Using copyOfRange() function
The copyOfRange() function is similar to the copyOf() function, but it copies the elements within the specified range from the array.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun <T> copyArray(src: Array<T>): Array<T> { return src.copyOfRange(0, src.size) } fun main() { val src = arrayOf<Int?>(1, 2, 3, 4, 5) val dest = copyArray(src) println(dest.contentToString()) // [1, 2, 3, 4, 5] } |
5. Custom Routine
You can even write custom logic for copying arrays in Kotlin. The algorithm can be implemented as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun <T> copyArray(src: Array<T>, dest: Array<T>) { for (i in src.indices) { dest[i] = src[i] } } fun main() { val src = arrayOf<Int?>(1, 2, 3, 4, 5) val dest = arrayOfNulls<Int>(src.size) copyArray(src, dest) println(dest.contentToString()) // [1, 2, 3, 4, 5] } |
That’s all about creating a shallow copy of an array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)