Kotlin – Get Element of Array at Specified Index

To get element of Array present at specified index in Kotlin language, use Array.get() method. Call get() method on this array and pass the index as argument. get() method returns the element.

Syntax

The syntax to call get() method on Array arr with index i passed as argument is

arr.get(i)
ADVERTISEMENT

Examples

In the following program, we take an array of strings, and get the element at index 2 using Array.get() method.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf("apple", "banana", "cherry", "mango")
    val element = arr.get(2)
    print("Element : $element")
}

Output

Element : cherry

If the index specified is out of bounds for the given array, then get() throws ArrayIndexOutOfBoundsException.

In the following program, we take an array of strings, and get the element at index 5 of the array arr. Since arr is only of size 4, get() throws ArrayIndexOutOfBoundsException.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf("apple", "banana", "cherry", "mango")
    val element = arr.get(5)
    print("Element : $element")
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
	at MainKt.main(Main.kt:3)

Conclusion

In this Kotlin Tutorial, we learned how to get element from Array at specified index using Array.get() method in Kotlin programming language with examples.