This article explores different ways to split an array into two parts in Kotlin. For an odd length array, the middle item should become part of the first array.

1. Custom Routine

We can write our custom routine for this simple task. The idea is to construct two arrays, and fill the first array with elements from the first half and the second array with elements from the second half of the original array.

Download Code

 
Output:

[1, 2, 3]
[4, 5]

2. Using System.arraycopy() function

The System.arraycopy() copies an array from a specified position in an array to a specified position in another array. We can use this as:

Download Code

 
Output:

[1, 2, 3]
[4, 5]

3. Using copyOfRange() function

Instead of manually creating the new array, you can call the copyOfRange() function that automatically declares the array and copies the elements.

Download Code

 
Output:

[1, 2, 3]
[4, 5]

That’s all about splitting an array into two parts in Kotlin.