Kotlin List elementAtOrNull()
Syntax & Examples


Syntax of List.elementAtOrNull()

The syntax of List.elementAtOrNull() extension function is:

fun <T> List<T>.elementAtOrNull(index: Int): T?

This elementAtOrNull() extension function of List returns an element at the given index or null if the index is out of bounds of this list.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the integers 10, 20, 30.
  • Then we use the elementAtOrNull function on list1 to access the element at index 1.
  • Since index 1 exists in list1, the element at that index, which is 20, is returned.
  • Finally, we print the value of result to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30);
    val result = list1.elementAtOrNull(1)
    print(result);
}

Output

20

2 Example

In this example,

  • We create a list named list2 containing the characters 'a', 'b', 'c'.
  • Then we use the elementAtOrNull function on list2 to access the element at index 5.
  • Since index 5 is out of bounds for list2, the function returns null.
  • Finally, we print the value of result to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list2 = listOf('a', 'b', 'c');
    val result = list2.elementAtOrNull(5)
    print(result);
}

Output

null

3 Example

In this example,

  • We create a list named list3 containing the strings "apple", "banana", "cherry".
  • Then we use the elementAtOrNull function on list3 to access the element at index 10.
  • Since index 10 is out of bounds for list3, the function returns null.
  • Finally, we print the value of result to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list3 = listOf("apple", "banana", "cherry");
    val result = list3.elementAtOrNull(10)
    print(result);
}

Output

null

Summary

In this Kotlin tutorial, we learned about elementAtOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.