Kotlin List lastIndex
Syntax & Examples
Syntax of List.lastIndex
The syntax of List.lastIndex extension property is:
val <T> List<T>.lastIndex: Int
This 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
list1
containing the characters'a', 'p', 'p', 'l', 'e'
. - We use the
lastIndex
property onlist1
to get the index of the last item in the list. - The index of the last item in
list1
is stored in the variableindex
. - Finally, we print the value of
index
to standard output using theprintln
function.
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
lastIndex
property onlist2
to get the index of the last item in the list. - Since
list2
is empty, thelastIndex
property returns-1
. - The result is stored in the variable
index
. - Finally, we print the value of
index
to standard output using theprintln
function.
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.