Kotlin Array - getOrElse() Function



The Kotlin array getOrElse() function is used to return the element at the given index if the index is present in an array. Otherwise, it returns the defaultValue function if the index is out of bounds of this array.

Syntax

Following is the syntax of Kotlin array getOrElse() function −

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

Parameters

This function accepts following parameters −

  • index: It represent an index for which an element will be returned.

  • defaultValue: It represent the default value that we need to set.

Return value

This function returns an element of an array. Otherwise; default value.

Example 1

Following is the basic example to demonstrate the use of getOrElse() function −

fun main(args: Array<String>){
   // let's create an array
   var list = arrayOf<String>("tutorialspoint", "Hyderabad", "India")
   // using getOrElse
   val elem = list.getOrElse(0){"tutorix"}
   println("$elem")
}

Output

On execution of the above code we get the following result −

tutorialspoint

Example 2

Now, let's see another example. Here, we use the getOrElse() function to display an element. Otherwise, default value −

fun main(args: Array<String>){
   // let's create an array
   var array = arrayOf<Int>(1, 2, 3, 4, 5, 6, 7)
   val elem = array.getOrElse(7){"no such index available"}
   print("$elem")
}

Output

After execution of the above code we get the following output −

no such index available 

Example 3

The below example creates an array and accessing the element of an array if available. Otherwise, displaying default value −

fun main(args: Array<String>) {
    val colors = arrayOf("Red", "Green", "Blue")

    // Accessing elements within the array bounds
    println(colors.getOrElse(1) { "Unknown" })
    println(colors.getOrElse(2) { "Unknown" })

    // Accessing elements out of the array bounds
    println(colors.getOrElse(3) { "Unknown" })
    println(colors.getOrElse(10) { "Unknown" })
}

Output

The above code produce following output −

Green
Blue
Unknown
Unknown
kotlin_arrays.htm
Advertisements