Kotlin Array - elementAtOrElse() Function



The Kotlin array elementAtOrElse() function returns the element of an array at a given index, or a default value if no such element exists or index is out of bounds of this array.

Syntax

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

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

Parameters

This function accepts the following parameters −

  • index: It represents the index of the element that need to be returned.

  • defaultValue: It represents a function that will be invoked when the index is greater than the length of an array.

Return value

This function returns an element of the given index.

Example 1

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

fun main(args: Array<String>) {
   val number: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
   val element = number.elementAtOrElse(1){10}
   println("element at index 1: $element")
}

Output

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

element at index 1: 2

Example 2

Now, let's see another example. We create an array with strings element. We then use the elementAtOrElse() function to get the element at the specified index −

fun main(args: Array<String>) {
   val strings: Array<String> = arrayOf("hii", "Hello", "tutorix", "tutorialspoint")
   val ele = strings.elementAtOrElse(3){15}
   println("element at index 3: $ele")
}

Output

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

element at index 3: tutorialspoint

Example 3

The example below display the default value if the index is not available in an array −

fun main(args: Array<String>) {
   // Create an array of characters from 'a' to 'z'
   val alphabet: Array<Char> = ('a'..'p').toList().toTypedArray()

   val default_val = alphabet.elementAtOrElse(16){"tutorialspoint"}
   
   println("This is default value: $default_val")
}

Output

The above code produce following output −

This is default value: tutorialspoint
kotlin_arrays.htm
Advertisements