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.

Download Code

2. Using System.arraycopy() function

Alternatively, you can use the System.arraycopy() function, which also creates a shallow copy of the array.

Download Code

3. Using copyOf() function

The copyOf() function returns a new array, a copy of the original array, resized to the given size.

Download Code

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.

Download Code

5. Custom Routine

You can even write custom logic for copying arrays in Kotlin. The algorithm can be implemented as follows:

Download Code

That’s all about creating a shallow copy of an array in Kotlin.