Kotlin Array.indexOfFirst() function
In Kotlin, the Array.indexOfFirst()
function is used to find the index of the first element in the array that satisfies the given predicate. If no such element is found, it returns -1.
In this tutorial, we’ll explore the syntax of the Array.indexOfFirst()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the Array.indexOfFirst()
function is as follows:
fun <T> Array<out T>.indexOfFirst(predicate: (T) -> Boolean): Int
where
Parameter | Description |
---|---|
predicate | A lambda function that takes the element of the array as an argument and returns true or false . |
The indexOfFirst()
function returns an Int
value that represents the index of the first element in the array that satisfies the given predicate
.
Examples for Array.indexOfFirst() function
1. Finding the Index of the First Even Number
In this example, we’ll use indexOfFirst()
to find the index of the first even number in the given array of integers numbersArray
.
Kotlin Program
fun main() {
val numbersArray = arrayOf(1, 3, 5, 7, 8, 9, 10, 11)
// Finding the index of the first even number
val indexOfFirstEven = numbersArray.indexOfFirst { it % 2 == 0 }
// Printing the original array and the result
println("Numbers Array\n${numbersArray.contentToString()}\n")
println("Index of the first even number\n$indexOfFirstEven")
}
Output
[1, 3, 5, 7, 8, 9, 10, 11]
Index of the first even number
4
Explanation
[1, 3, 5, 7, 8, 9, 10, 11] ← given array
* * ← even numbers
0 1 2 3 4 5 6 7 ← indices
↑
indexOfFirst even number
2. Finding the Index of an Element that is not in Array using indexOfFirst()
In this example, we’ll use indexOfFirst()
in a scenario where the given array has no element that satisfies the given predicate/condition.
In the following program, the array numbersArray
has no even numbers in it, and we are trying to find the index of first even number.
Kotlin Program
fun main() {
val numbersArray = arrayOf(1, 3, 5, 7, 9, 11)
// Finding the index of the first even number
val indexOfFirstEven = numbersArray.indexOfFirst { it % 2 == 0 }
// Printing the original array and the result
println("Numbers Array\n${numbersArray.contentToString()}\n")
println("Index of the first even number\n$indexOfFirstEven")
}
Output
Numbers Array
[1, 3, 5, 7, 9, 11]
Index of the first even number
-1
Since, there is no element that matches the given predicate, Array.indexOfFirst()
returns -1
.
Summary
In this tutorial, we’ve covered the Array.indexOfFirst()
function in Kotlin, its syntax, and how to use it to find the index of the first element that satisfies a given predicate.