Kotlin List – Get the index of Last Element

To get the last index, or say index of last element, in the List, read the lastIndex property of this List.

The Kotlin List.lastIndex property returns the index of last element in the given list.

Syntax of List.lastIndex

The syntax of List.lastIndex property is

list.lastIndex

Return Value

List.lastIndex returns the an integer representing the index of the last item in the list. But, if the list is empty, the property returns -1.

ADVERTISEMENT

Example 1: Get Last Index in List

In this example, we will take a list of elements of type string. We will access the property, lastIndex, of this list and print it to console.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de", "ef", "fg", "gh")
    val lastIndexOfList = list1.lastIndex
    print("Last index of this list is $lastIndexOfList")
}

Output

Last index of this list is 6

Example 2: List.lastIndex for Empty List

Let us programmatically if the lastIndex property returns -1 if the list is empty.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf<String>()
    val lastIndexOfList = list1.lastIndex
    print("Last index of this list is $lastIndexOfList")
}

Output

Last index of this list is -1

Conclusion

In this Kotlin Tutorial, we learned how to use lastIndex property to find the index of last element in the list.