Kotlin Array.getOrElse()

Kotlin Array.getOrElse() Tutorial

The Array.getOrElse() function in Kotlin is used to retrieve the element at the specified index of the array. If the index is within the valid range of the array, it returns the element at that index. However, if the index is out of bounds, it returns the result of the provided lambda function or a default value.

This tutorial will explore the syntax of the Array.getOrElse() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.getOrElse() function is as follows:

fun <T> Array<out T>.getOrElse(
    index: Int,
    defaultValue: (Int) -> T
): T

where

ParameterDescription
indexIndex of the element required in the array.
defaultValueThe default value to return when the given index is out of bounds for the array.
Parameters of Array.getOrElse()

Examples for Array.getOrElse() function

1. Retrieving Element at a Valid Index

In this example, we’ll use the getOrElse() function to retrieve the element at a valid index within the array.

Kotlin Program

fun main() {
    val fruitsArray = arrayOf("Apple", "Banana", "Orange", "Mango")

    // Using getOrElse() to retrieve the element at a valid index
    val element = fruitsArray.getOrElse(2) { "Unknown Fruit" }

    // Printing the array and the result
    println("Fruits Array:\n${fruitsArray.contentToString()}\n")
    println("Element at index 2\n$element")
}

Output

Fruits Array:
[Apple, Banana, Orange, Mango]

Element at index 2
Orange

2. Retrieving Element at an Invalid Index

In this example, we’ll use the getOrElse() function to handle the case where the index is out of bounds.

Kotlin Program

fun main() {
    val fruitsArray = arrayOf("Apple", "Banana", "Orange", "Mango")

    // Using getOrElse() to retrieve the element at an invalid index
    val element = fruitsArray.getOrElse(10) { "Unknown Fruit" }

    // Printing the array and the result
    println("Fruits Array:\n${fruitsArray.contentToString()}\n")
    println("Element at index 10\n$element")
}

Output

Fruits Array:
[Apple, Banana, Orange, Mango]

Element at index 10
Unknown Fruit

Summary

In this tutorial, we’ve covered the Array.getOrElse() function in Kotlin, its syntax, and how to use it to retrieve elements based on index, handling both valid and invalid index scenarios. This function is useful for providing default values or performing fallback actions when accessing array elements.