
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
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