This article explores different ways to find the index of an element in a Kotlin List.

1. Using indexOf() function

The recommended solution to get the index of an element in a list is with the indexOf() library function. It returns the index of the first occurrence of the provided element in the list, or -1 if the element is not present.

Download Code

2. Using withIndex() function

The idea here is to get an iterable containing the index of each element of the list and the element itself using the withIndex() function. Then return the index of the first pair that match the given value. This would translate to the following code:

Download Code

3. Using find() function

Another viable alternative is to filter the indices containing the given element using the find() function, which returns the first element matching the given predicate, or null if no such element exists. This would translate to a simple code below:

Download Code

4. Using Loop

Following is an equivalent version using the for loop, which returns the index of the first occurrence, or -1 if no matching element is found.

Download Code

That’s all about finding the index of an element in a Kotlin List.