Each element of a list has an index. Kotlin list indexes start from zero. The last element has len-1 index.
Kotlin List Indexing Example
The example presents Kotlin List indexing operations.
fun main() { val words = listOf("pen", "cup", "dog", "person", "cement", "coal", "spectacles", "cup", "bread") val w1 = words.get(0) println(w1) val w2 = words[0] println(w2) val i1 = words.indexOf("cup") println("The first index of cup is $i1") val i2 = words.lastIndexOf("cup") println("The last index of cup is $i2") val i3 = words.lastIndex println("The last index of the list is $i3") }
Output:
pen pen The first index of cup is 1 The last index of cup is 7 The last index of the list is 8 This is the output.
Comments
Post a Comment