Kotlin List.lastIndex – Examples

Kotlin List.lastIndex

The Kotlin List.lastIndex property returns the index of the last item in the list or -1 if the list is empty.

Syntax

List.lastIndex

Example 1: Get the last index of given list

In this example,

  1. Given a list of strings in list1. The list has five values.
  2. Read the lastIndex property of the list using dot operator.
  3. You may print the last index to output.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "d", "e")
    val lastIndex = list1.lastIndex
    print(lastIndex)
}

Output

4

Example 2: Get the last index of an empty list

In this example,

  1. Given an empty list in list1.
  2. Read the lastIndex property of this list list1 using dot operator.

Program

fun main(args: Array<String>) {
    val list1 = listOf<String>()
    val lastIndex = list1.lastIndex
    print(lastIndex)
}

Output

-1