This article explores different ways to remove the last item from an array in Kotlin.

Arrays in Kotlin hold a fixed number of values of a single type. The fixed length of the array is decided upon its creation, which remains fixed post creation. So, there is no standard way to remove values from it. However, we can create a new array containing all values from the original array except the last. There are several plausible ways to do that in Kotlin:

1. Using copyOf() function

The standard solution to remove the last item from an array is using the copyOf() function, which can copy desired elements of the original array into a new array starting from the beginning.

Download

Output:

[5, 3, 4, 7, 6]

 
Similar to the copyOf() function, we have the copyOfRange() function, which can accept a range of elements to copy to the new array.

Download

Output:

[5, 3, 4, 7, 6]

2. Using System.arraycopy() function

Another option is to leverage the System.arraycopy() function, which can copy the specified range from the source array to the destination array.

Download

Output:

[5, 3, 4, 7, 6]

3. Using Range

Alternately, we can generate a sequentially ordered range between 0 (inclusive) and lastIndex (exclusive), transform each index to the corresponding element in the original array using the map() function, and return an array of Int containing all the mapped elements.

Download

Output:

[5, 3, 4, 7, 6]

That’s all about removing the last item from an array in Kotlin.