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 integers10, 20, 30
. - Then we use the
elementAtOrElse
function onlist1
to access the element at index1
. - Since index
1
exists inlist1
, the element at that index, which is20
, is returned. - We specify a default value
100
as the second argument ofelementAtOrElse
, but it's not used because the index1
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 onlist2
to access the element at index5
. - Since index
5
is out of bounds forlist2
, 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 onlist3
to access the element at index10
. - Since index
10
is out of bounds forlist3
, 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.