Kotlin List getOrElse()
Syntax & Examples
Syntax of List.getOrElse()
The syntax of List.getOrElse() extension function is:
fun <T> List<T>.getOrElse( index: Int, defaultValue: (Int) -> T ): T
This getOrElse() extension function of List 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.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing strings. - We use the
getOrElse
function to retrieve the element at index 5 from the list. Since the index is out of bounds, the default value"default"
is returned. - We print the retrieved element to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry");
val element = list.getOrElse(5) { "default" }
println(element);
}
Output
default
2 Example
In this example,
- We create a list named
list
containing integers. - We use the
getOrElse
function to retrieve the element at index 1 from the list. The element at index 1 is20
. - We print the retrieved element to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(10, 20, 30);
val element = list.getOrElse(1) { 0 }
println(element);
}
Output
20
3 Example
In this example,
- We create a list named
list
containing characters. - We use the
getOrElse
function to retrieve the element at index 3 from the list. Since the index is out of bounds, the default value'z'
is returned. - We print the retrieved element to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c');
val element = list.getOrElse(3) { 'z' }
println(element);
}
Output
z
Summary
In this Kotlin tutorial, we learned about getOrElse() extension function of List: the syntax and few working examples with output and detailed explanation for each example.