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 ): TThis 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
listcontaining strings. - We use the
getOrElsefunction 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
listcontaining integers. - We use the
getOrElsefunction 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
listcontaining characters. - We use the
getOrElsefunction 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.