Kotlin List – Get Element at Index
To get the element from a List in Kotlin present at specific index, call get()
function on this list and pass the index as argument to get()
function.
The Kotlin List.get() function returns the element at the specified index in this list.
Syntax of List.get()
The syntax of List.get() function is
list.get(index)
Parameter | Description |
---|---|
index | Required. An integer the specifies the position of element in the list. |
Return Value
The List.get() function returns the element at index
.
Example 1: Get Element in List
In this example, we will take a list of strings, and get the element at index 2.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("ab", "bc", "cd", "de", "ef")
val index = 2
val element = list1.get(index)
print("Element at index $index is $element")
}
Output
Element at index 2 is cd
Example 2: Negative Index to get() Function
List.get() function throws java.lang.ArrayIndexOutOfBoundsException if you provide a negative index.
In this example, we will take a list of elements, and call get() method on this list with an index of -2. get() function should throw ArrayIndexOutOfBoundsException.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("ab", "bc", "cd", "de", "ef")
val index = -2
val element = list1.get(index)
print(element)
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2
at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4350)
at HelloWorldKt.main(HelloWorld.kt:4)
Conclusion
In this Kotlin Tutorial, we learned how to get an element at specific index, using Kotlin List.get() function.