Kotlin List.elementAt()
The Kotlin List.elementAt() function returns an element at the given index or throws an IndexOutOfBoundsException if the index is out of bounds of this list.
Syntax
List.elementAt(index)
Kotlin Example 1: Get element at index=2 from List
In this example,
- Take a list of strings: list1.
- Take a value for index, say 2,
- Call elementAt() function on the list, and pass index as arguemnt to the function. The function returns element in list at the specified index.
Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c", "d", "e")
val index = 2
val result = list1.elementAt(index)
print(result)
}
Output
c
Kotlin Example 2: Get element at index that is out of bounds for the given List
In this example,
- Take a list of strings:
list1
. - Take a value for index, say 14, such that index is greater than size of list.
- Call elementAt() function on the list, and pass index as arguemnt to the function. Since, index is out of bounds of the list indices, the function throws IndexOutOfBoundsException.
Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c", "d", "e")
val index = 14
val result = list1.elementAt(index)
print(result)
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 14
at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4350)
at KotlinExampleKt.main(KotlinExample.kt:4)