Kotlin Array first()
In Kotlin, the Array first()
function is used to obtain the first element of the array that satisfies the given predicate(condition). It returns the element if it finds the element, or throws a NoSuchElementException
if the array is empty.
If no predicate is given, then first()
function returns the first element in the array.
In this tutorial, we’ll explore the syntax of the first()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the first()
function is as follows:
fun <T> Array<out T>.first(): T
fun <T> Array<out T>.first(predicate: (T) -> Boolean): T
where
Parameter | Description |
---|---|
predicate | A lambda function that takes the element of array as argument and returns true or false . |
If no element satisfies the predicate or if the array is empty, the function throws a NoSuchElementException
.
Examples for Array first() function
1. Using first() with an Array of Numbers
In this example, we’ll use first()
to obtain the first element of an array of numbers numbersArray
that satisfies the condition that the element is exactly divisible by 3
.
Kotlin Program
fun main() {
val numbersArray = arrayOf(10, 15, 20, 25, 30)
// Using first() to obtain the first element that is exactly divisible by 3
val firstElement = numbersArray.first{it % 3 == 0}
println("First Element (exactly divisible by 3) : $firstElement")
}
Output
First Element (exactly divisible by 3) : 15
2. Using first() with no predicate
We have already learnt that if no predicate is given to first() function, then it returns the first element in the array.
Kotlin Program
fun main() {
val numbersArray = arrayOf(10, 15, 20, 25, 30)
// Using first() to obtain the first element
val firstElement = numbersArray.first()
println("First Element : $firstElement")
}
Output
First Element : 10
3. Using first() with an Empty Array
In this example, we’ll use first()
with an empty array to demonstrate the NoSuchElementException
when the array is empty.
Kotlin Program
fun main() {
val numbersArray = intArrayOf()
// Using first() to obtain the first element
val firstElement = numbersArray.first()
println("First Element : $firstElement")
}
Output
Exception in thread "main" java.util.NoSuchElementException: Array is empty.
at kotlin.collections.ArraysKt___ArraysKt.first(_Arrays.kt:1045)
at MainKt.main(Main.kt:5)
at MainKt.main(Main.kt)
You may use a try-catch block to handle this exception.
Summary
In this tutorial, we’ve covered the first()
function in Kotlin arrays, its syntax, and how to use it to obtain the first element of an array. Remember to handle the NoSuchElementException
when using this function with an empty array to prevent runtime errors.