Kotlin List.get() – Examples

Kotlin List.get()

The Kotlin List.get() function returns the element at the specified index in the list.

Syntax

List.get(index)

Example 1

In this example,

  1. Take a list of strings.
  2. Initialize a val, index, with specific integer.
  3. Call get() function on the list with index passed as argument. The function should return the element present at that specific index.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "v", "k", "m")
    val index = 3
    val result = list1.get(index)
    print(result)
}

Output

k

Example 2

In this example,

  1. Take a list of strings.
  2. Initialize an integer val, index, such that the index is out of range for the list.
  3. Call get() function on the list with index passed as argument. The function should throw java.lang.ArrayIndexOutOfBoundsException.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "v", "k", "m")
    val index = 35
    val result = list1.get(index)
    print(result)
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 35
	at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4350)
	at KotlinExampleKt.main(KotlinExample.kt:4)