Clone an array in Kotlin
This post will discuss various functions to clone an array in Kotlin.
1. Using clone() function
|
1 2 3 4 5 6 7 8 9 10 |
fun <T> copy(arr: Array<T>): Array<T> { return arr.clone() } fun main() { val from = arrayOf(6, 7, 5, 2, 4) val to = copy(from) println(to.contentToString()) // [6, 7, 5, 2, 4] } |
2. Using copyOf() function
|
1 2 3 4 5 6 7 8 9 10 |
fun <T> copy(arr: Array<T>): Array<T?> { return arr.copyOf(arr.size) } fun main() { val from = arrayOf(6, 7, 5, 2, 4) val to = copy(from) println(to.contentToString()) // [6, 7, 5, 2, 4] } |
3. Using copyOfRange() function
|
1 2 3 4 5 6 7 8 9 10 |
fun <T> copy(arr: Array<T>): Array<T> { return arr.copyOfRange(0, arr.size) } fun main() { val from = arrayOf(6, 7, 5, 2, 4) val to = copy(from) println(to.contentToString()) // [6, 7, 5, 2, 4] } |
4. Using arraycopy() function
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun copy(arr: Array<Int>): Array<Int?> { val to = arrayOfNulls<Int>(arr.size) System.arraycopy(arr, 0, to, 0, arr.size) return to } fun main() { val from = arrayOf(6, 7, 5, 2, 4) val to = copy(from) println(to.contentToString()) // [6, 7, 5, 2, 4] } |
That’s all about cloning 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 :)