Kotlin Array - elementAtOrNull() Function



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

Syntax

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

fun <T> Array<out T>.elementAtOrNull(index: Int): T?

Parameters

This function accepts an index as a parameter, it represents the index of the element that need to be returned.

Return value

This function returns an element of the given index.

Example 1

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

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

Output

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

element at index 1: 5

Example 2

Now, let's see another example. Here, we use the elementAtOrNull() function to retrieve the element at the specified index. If the index isn't available, the function returns null −

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

Output

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

element at index 4: null

Example 3

The example below creates an empty array. We then use the elementAtOrNull() function to see what output will get in an empty array? −

fun main(args: Array<String>) {
   val number: Array<Int>= emptyArray()
   val ele = number.elementAtOrNull(1)
   println("element at index 1: $ele")
}

Output

The above code produce following output if an array is empty −

element at index 1: null
kotlin_arrays.htm
Advertisements