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 ): TThis 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 ): TThis 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
list1containing the integers10, 20, 30. - Then we use the
elementAtOrElsefunction onlist1to access the element at index1. - Since index
1exists inlist1, the element at that index, which is20, is returned. - We specify a default value
100as the second argument ofelementAtOrElse, but it's not used because the index1is valid. - Finally, we print the value of
resultto 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
list2containing the characters'a', 'b', 'c'. - Then we use the
elementAtOrElsefunction onlist2to access the element at index5. - Since index
5is out of bounds forlist2, the default value function{ 'z' }is called, and it returns'z'. - Finally, we print the value of
resultto 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
list3containing the strings"apple", "banana", "cherry". - Then we use the
elementAtOrElsefunction onlist3to access the element at index10. - Since index
10is out of bounds forlist3, the default value function{ "not found" }is called, and it returns"not found". - Finally, we print the value of
resultto 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.