This article explores different ways to remove the first element from a List in Kotlin.

1. Using removeAt() function

The removeAt() function removes an element at the specified index from a mutable list. It can be called as follows:

Download Code

 
We should place a bound check before calling the removeAt() function, otherwise java.lang.IndexOutOfBoundsException will be thrown.

Download Code

2. Using clear() function

Another alternative is to get a view of the first element of the list and call the clear() function on it. This can be done using the subList() function, which returns a sublist that is “backed” by the original list, as shown below.

Download Code

 
As with the previous approach, it is safe to check for an empty list before invoking the sublist() function.

Download Code

3. Using drop() function

Both the above solutions in-place modify the list. To get a new list without touching the original list, use the drop(n) function instead. It returns a list containing all elements except the first n elements.

Download Code

4. Using filterIndexed() function

Finally, we can use the filterIndexed() function to remove the first element from the list. It returns a new list containing elements matching the specified predicate function, that takes the index of an element and the element itself and returns the result of predicate evaluation on the element.

Download Code

That’s all about removing the first element from a List in Kotlin.