This article explores different ways to copy two-dimensional arrays in Kotlin. The column size may or may not be fixed for the two-dimensional array.

1. Using clone() function

The idea is to iterate over each row of the original array and then call the clone() function to clone each row.

Download Code

Output:

[1, 2, 3, 4, 5]
[6, 7, 8, 9]
[10, 11, 12]

 
Alternatively, we can use the map() function to shorten the code and improve its readability:

Download Code

Output:

[1, 2, 3, 4, 5]
[6, 7, 8, 9]
[10, 11, 12]

2. Using System.arraycopy() function

We can also use the System.arraycopy() function to clone each row of the two-dimensional array. The following code example demonstrates the invocation of the System.arraycopy() function to create a copy of a two-dimensional array.

Download Code

Output:

[1, 2, 3, 4, 5]
[6, 7, 8, 9]
[10, 11, 12]

3. Using copyOf() function

Since all elements in each row are copied to the new array, the System.arraycopy() call can be avoided. We can improve the readability of the above code by using the copyOf() function. Here’s an equivalent version using the copyOf() function.

Download Code

Output:

[1, 2, 3, 4, 5]
[6, 7, 8, 9]
[10, 11, 12]

4. Nested Loop

Finally, we can use the nested for-loop for copying a two-dimensional array in Kotlin. This is demonstrated below:

Download Code

Output:

[1, 2, 3, 4, 5]
[6, 7, 8, 9]
[10, 11, 12]

That’s all about copying a two-dimensional array in Kotlin.