Kotlin List lastIndex
Syntax & Examples
Syntax of List.lastIndex
The syntax of List.lastIndex extension property is:
val <T> List<T>.lastIndex: IntThis lastIndex extension property of List returns the index of the last item in the list or -1 if the list is empty.
✐ Examples
1 Example
In this example,
- We create a list named
list1containing the characters'a', 'p', 'p', 'l', 'e'. - We use the
lastIndexproperty onlist1to get the index of the last item in the list. - The index of the last item in
list1is stored in the variableindex. - Finally, we print the value of
indexto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("a", "p", "p", "l", "e");
val index = list1.lastIndex;
println(index);
}Output
4
2 Example
In this example,
- We create an empty list named
list2. - We use the
lastIndexproperty onlist2to get the index of the last item in the list. - Since
list2is empty, thelastIndexproperty returns-1. - The result is stored in the variable
index. - Finally, we print the value of
indexto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list2 = emptyList<String>();
val index = list2.lastIndex;
println(index);
}Output
-1
Summary
In this Kotlin tutorial, we learned about lastIndex extension property of List: the syntax and few working examples with output and detailed explanation for each example.