This article explores different ways to retrieve the last item from a List in Kotlin.

1. Using last() function

A simple and concise solution is to use the last() library function, which returns the last element from the list. It can be used as follows:

Download Code

 
This, however, throws a java.util.NoSuchElementException if the list is empty. To handle it, you can use the lastOrNull() library function which returns the last element, or null if the list is empty.

Download Code

2. Using lastIndex property

Another solution to retrieve the last element is using the expression L.get(L.lastIndex). Here L is our list and lastIndex returns the index of the last item in the list.

Download Code

 
To handle the java.util.IndexOutOfBoundsException when the list is empty, place a boundary check on the list before accessing the last index.

Download Code

3. Using takeLast() function

If you need to retrieve the last few elements from the list, the recommended solution is to call the takeLast() library function. Note that it returns a list.

Download Code

 
To “remove” the last few elements from the list and get the remaining elements, use the dropLast() library function.

Download Code

4. Using Loop

Finally, you can simply iterate through the array and return the last element. However, this is a very inefficient approach to use for an index-based ordered list.

Download Code

That’s all about retrieving the last item from a List in Kotlin.