Kotlin List.lastIndex Property

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

listlastIndex

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.

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 lastIndex property to find the index of last element in the list.