Kotlin List elementAtOrElse()
Syntax & Examples


Syntax of List.elementAtOrElse()

There are 2 variations for the syntax of List.elementAtOrElse() extension function. They are:

1.
fun <T> List<T>.elementAtOrElse( index: Int, defaultValue: (Int) -> T ): T

This extension function returns an element at the given index or the result of calling the defaultValue function if the index is out of bounds of this list.

2.
fun <T> Iterable<T>.elementAtOrElse( index: Int, defaultValue: (Int) -> T ): T

This extension function returns an element at the given index or the result of calling the defaultValue function if the index is out of bounds of this collection.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the integers 10, 20, 30.
  • Then we use the elementAtOrElse 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.
  • We specify a default value 100 as the second argument of elementAtOrElse, but it's not used because the index 1 is valid.
  • 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.elementAtOrElse(1) { 100 }
    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 elementAtOrElse function on list2 to access the element at index 5.
  • Since index 5 is out of bounds for list2, the default value function { 'z' } is called, and it returns 'z'.
  • 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.elementAtOrElse(5) { 'z' }
    print(result);
}

Output

z

3 Example

In this example,

  • We create a list named list3 containing the strings "apple", "banana", "cherry".
  • Then we use the elementAtOrElse function on list3 to access the element at index 10.
  • Since index 10 is out of bounds for list3, the default value function { "not found" } is called, and it returns "not found".
  • 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.elementAtOrElse(10) { "not found" }
    print(result);
}

Output

not found

Summary

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