Kotlin Array.getOrNull() Tutorial
The Array.getOrNull()
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 null
.
This tutorial will explore the syntax of the Array.getOrNull()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the Array.getOrNull()
function is as follows:
fun <T> Array<out T>.getOrNull(
index: Int
): T?
where
Parameter | Description |
---|---|
index | Index of the element required in the array. |
Examples for Array.getOrNull() function
1. Retrieving Element at a Valid Index
In this example, we’ll use the getOrNull()
function to retrieve the element at a valid index within the array.
Kotlin Program
fun main() {
val fruitsArray = arrayOf("Apple", "Banana", "Orange", "Mango")
// Using getOrNull() to retrieve the element at a valid index
val element = fruitsArray.getOrNull(2)
// 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 getOrNull()
function to handle the case where the index is out of bounds.
Kotlin Program
fun main() {
val fruitsArray = arrayOf("Apple", "Banana", "Orange", "Mango")
// Using getOrNull() to retrieve the element at an invalid index
val element = fruitsArray.getOrNull(10)
// 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
null
Summary
In this tutorial, we’ve covered the getOrNull()
function in Kotlin arrays, its syntax, and how to use it to retrieve elements based on index, handling both valid and invalid index scenarios. This function is useful when you need to check for out-of-bounds access and gracefully handle such situations by returning null
.