Kotlin Array - getOrNull() Function



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

Syntax

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

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

Parameters

This function accepts index as parameters. Which represent an index for which an element will be returned.

Return value

This function returns an element of an array. Otherwise; null.

Example 1

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

fun main(args: Array<String>){
   // let's create an array
   var array = arrayOf<Int>(1, 2, 3, 4, 5)
   // using getOrNull
   val elem = array.getOrNull(0)
   println("element at index 0: $elem")
}

Output

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

element at index 0: 1

Example 2

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

fun main(args: Array<String>){
   // let's create an array
   var array = arrayOf<String>("tutorialspoint", "India", "tutorix", "India")
   val elem = array.getOrNull(4)
   print("element at index 4: $elem")
}

Output

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

element at index 4: null

Example 3

The below example will return an element or not if we pass the index as -1 −

fun main(args: Array<String>){
   // let's create an array
   var array = arrayOf<Int>(1, 2, 3, 4, 5)
   // using getOrNull
   val elem = array.getOrNull(-1)
   println("element at index -1: $elem")
}

Output

The above code produce following output −

element at index -1: null
kotlin_arrays.htm
Advertisements